﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using DevExpress.XtraEditors;
using MINERP.BLL.CustomerManage;
using DevExpress.XtraGrid.Views.Grid.ViewInfo;
using System.Threading;
using System.Runtime.InteropServices;

using Leadtools;
using Leadtools.Codecs;
using Leadtools.WinForms;
using DevExpress.XtraGrid.Views.Grid;
using System.Net;
using System.Net.Sockets;
using DevExpress.XtraEditors.Repository;
using System.Configuration;
using MINERP.COM;
using MINERP.ComControls;
using DevExpress.XtraNavBar;
using MINERP.ComControls.Extension;

namespace MINERP.CustomerManage.StartOrder
{
    public partial class FrmStartOrder : FrmParent
    {
        //参数
        bool IsOpenedOrder = false;                     //是否真的开了单
        private BLL.CustomerManage.StartOrderBLL SOBLL = new MINERP.BLL.CustomerManage.StartOrderBLL();
        List<StartOrderBLL.ProductInfo> productListShop;   //商户特有的产品信息
        List<StartOrderBLL.STProductDisplay> ListProductDisplayShop;    //商户特有的产品显示信息
        List<StartOrderBLL.STProductDisplay> ListProductDisplayUsually; //常用产品
        List<StartOrderBLL.STProductDisplay> SXList = new List<StartOrderBLL.STProductDisplay>();           //助记码筛选的产品集合
        List<StartOrderBLL.STProductDisplay> FilterDisplayProduct = new List<StartOrderBLL.STProductDisplay>();//按类别分类的原始产品信息 
        List<StartOrderBLL.STProductDisplay> FilterDisplayProductShop = new List<StartOrderBLL.STProductDisplay>();//按类别分类的商户产品信息 
        List<StartOrderBLL.STProductDisplay> FilterUsually = new List<StartOrderBLL.STProductDisplay>();           //常用产品分类
        //List<StartOrderBLL.ProductInfo> ProductDataSource = new List<StartOrderBLL.ProductInfo>();      //上部显示的产品信息
        //List<StartOrderBLL.STProductTech> productTechList;  //所有产品的流程
        List<StartOrderBLL.STProductTech> singleProductTech;    //单个产品流程
        List<StartOrderBLL.ProductInfo> ListProduct = new List<StartOrderBLL.ProductInfo>();    //订单的产品集合(设置后的产品信息)
        List<StartOrderBLL.STPaperType> ListPaperType;          //纸型集合
        List<StartOrderBLL.STPaperFace> ListPaperFace;          //纸面集合
        List<StartOrderBLL.STShop> ListShop;
        string TotalPath;                                       //等待开单的总路径
        bool isAddOldTech = false;                              //是否是已添加产品
        int DragType;                                           //拖曳的类型 1客户实体 2产品实体 3产品模板
        string BagCode = "";
        int OrderID = 0;
        double OrderHours = 0;                                  //生成订单的最长时间(以用时最长的产品为标准)
        bool IsSetFetchTime = false;                            //是否已设置取件时间
        bool IsOrderBagExists = false;                          //订单包号是否已存在
        string currentShopPath = "";                              //当前开单的商户路径
        string lastShopName = "";                               //上一个商户的名字
        int CurrentShopId = 0;                                  //当前商户Id
        bool IsNeedCheckPhotoRepeat = false;                         //检查照片是否重复
        TcpClient client = null;                                //tcp客户端(crc验证通信使用)
        Socket clientSocket = null;                             //socket客户端(crc验证通信使用)
        public delegate void DelSetStartOrderPath();            //设置开单树
        public DelSetStartOrderPath InvokeSetStartOrderPath;
        public static bool IsGetTree = false;                   //是否已加载目录树
        public static bool IsOpenStartOrder = false;            //是否已实例化开单页面。 只有这两个条件都满足时，才能加载生产目录树
        [DllImport("shell32.dll ")]
        private static extern int ShellExecute(IntPtr hwnd, StringBuilder lpszOp, StringBuilder lpszFile, StringBuilder lpszParams, StringBuilder lpszDir, int FsShowCmd);

        public List<MODEL.CustomerManage.StartOrder.User> AllUser;//保存全部员工(选择某商户某节点默认员工使用)
        public List<MODEL.CustomerManage.StartOrder.ShopTechUser> Stu = new List<MODEL.CustomerManage.StartOrder.ShopTechUser>();   //某商户某节点的默认操作员工
        public List<MODEL.CustomerManage.StartOrder.ProductOutShop> Po = new List<MINERP.MODEL.CustomerManage.StartOrder.ProductOutShop>(); //加载产品所有的委外商
        public int SelectedUserId = 0;                          //重新选择的操作员工
        public string SelectedUserName = "";                    //重新选择的操作员工名
        public int SelectedOutShopId = 0;                       //重新选择的委外商
        public string SelectedOutShopName = "";                 //重新选择的委外商名

        private bool ceProductWithoutPhotoClick = true;           //是否鼠标点击  不需要照片的产品类型更改
        private bool ceProductOutReturnClick = true;           //是否鼠标点击  不需要照片的产品类型更改

        public List<MODEL.CustomerManage.StartOrder.Printer> AllPrinter;    //所有打印机
        public string LayoutPath = Application.StartupPath + "\\Layout";

        public List<MINERP.MODEL.CustomerManage.StartOrder.CommonChargeItemDDO> AllCostItem;//所有收费项目
        //public List<MINERP.MODEL.CustomerManage.StartOrder.CommonChargeItemDDO> CheckCostItem;//所有收费项目，h
        List<StartOrderBLL.STProductTech> CommonProductTechBeforePrint = new List<StartOrderBLL.STProductTech>();    //单个产品流程
        public List<StartOrderBLL.STPaperType> CurrShopPaperType = new List<StartOrderBLL.STPaperType>();
        //属性
        public int UserID { get; set; }                         //开单人
        public string UserName { get; set; }                    //开单员名称

        public FrmManage Manage { get; set; }                   //客服页面
        public int PhotoNum { get; set; }                       //照片数量(一次性设置多张照片的数量使用)

        public FrmStartOrder()
        {
            InitializeComponent();
            base.InitiAuthority();

            gvProductList.ShowRowIndicator(50);
            gvProduct.ShowRowIndicator(50);
            gridView2.ShowRowIndicator(50);
            gvProductCategory.ShowRowIndicator(50);
            gvUsuallyUse.ShowRowIndicator(50);

        }
        private void FrmStartOrder_Load(object sender, EventArgs e)
        {
            try
            {
                //UserID = 2;     //测试使用
                //UserName = "系统管理员";

                IsOpenedOrder = false;                      //表示还未真正开单
                //订单包号
                SOBLL.AddOrderBagTemp(out OrderID, out BagCode, UserID);
                if (btnCodeType.Text == "自动")
                    SetOrderBagCode();
                //订单名称默认也是订单包号
                txtOrderName.Text = BagCode;
                //绑定商户下拉列表
                ListShop = SOBLL.GetShopList();
                txtOrderName.Text = BagCode;
                foreach (StartOrderBLL.STShop s in ListShop)
                {
                    cbShopName.Properties.Items.Add(s.ShopName);
                }
                //所有纸型
                ListPaperType = new List<StartOrderBLL.STPaperType>();
                ListPaperType = SOBLL.GetPaperType();
                foreach (StartOrderBLL.STPaperType ptype in ListPaperType)
                {
                    cbPaperType.Properties.Items.Add(ptype.PaperTypeName);
                    cbShopPaperType.Properties.Items.Add(ptype.PaperTypeName);
                    ((DevExpress.XtraEditors.Repository.RepositoryItemComboBox)repositoryItemComboBoxPaperType).Items.Add(ptype.PaperTypeName);
                }
                //所有纸面
                ListPaperFace = new List<StartOrderBLL.STPaperFace>();
                ListPaperFace = SOBLL.GetPaperFace();
                foreach (StartOrderBLL.STPaperFace pface in ListPaperFace)
                {
                    if (pface.PaperFaceName == "任意")
                        continue;
                    cbPaperFace.Properties.Items.Add(pface.PaperFaceName);
                    cbShopPaperFace.Properties.Items.Add(pface.PaperFaceName);
                    ((DevExpress.XtraEditors.Repository.RepositoryItemComboBox)repositoryItemComboBoxPaperFace).Items.Add(pface.PaperFaceName);
                }
                gcProductList.DataSource = ListProduct;

                //单位
                string gunit = Properties.Settings.Default.PreviousUnit;
                cbUnit.Text = gunit;

                //高宽单位
                string unit = cbUnit.Text;
                int uIndex = unit.IndexOf("(");
                string uunit = unit.Substring(0, uIndex);

                //加载待开单目录树
                TotalPath = SOBLL.GetStartOrderPath();
                InvokeSetStartOrderPath = new DelSetStartOrderPath(AddStartOrderPath);
                IsOpenStartOrder = true;
                SetStartOrderTree(this);
                //设置时间
                SetTime();
                //清空商户特有产品组和助记码快速筛选的产品组
                bcProductCommon.Groups.Clear();
                bcProduct.Groups.Clear();
                bcUsuallyUse.Groups.Clear();
                //默认显示商户特有的产品
                xtraTabControl1.SelectedTabPage = xtraTabPage1;
                //按分辨率设置页面样式
                SetFormStyle();
                //设置常用产品的数量
                SetUsuallyUseNum();
                //tcp连接
                SetTcpConnect();
                //是否crc校验
                SetCrc();
                //取得所有员工(在设置节点操作员时使用)
                AllUser = SOBLL.GetAllUser();
                //取得所有打印机(在设置产品的默认打印机时使用)
                AllPrinter = SOBLL.GetAllPrinter();
                BindPrinter();
                Cursor = Cursors.Default;
                CommonProductTechBeforePrint = SOBLL.GetAllFlowTechBeforPrint(); ;
                //取到所有的收费项目
                AllCostItem = SOBLL.GetAllCostItems();

                foreach (MINERP.MODEL.CustomerManage.StartOrder.CommonChargeItemDDO ddo in AllCostItem)
                {
                    repositoryItemCheckedComboBoxEditCostType.Items.Add(ddo.ItemName);
                }
                //((RepositoryItemComboBox)gvProduct.Columns[10].ColumnEdit).SelectedValueChanged += new System.EventHandler(gvProduct_TypeSelectedValueChanged);
                //((RepositoryItemComboBox)gvProduct.Columns[11].ColumnEdit).SelectedValueChanged += new System.EventHandler(gvProduct_FaceSelectedValueChanged);
                if (!Directory.Exists(LayoutPath))
                {
                    Directory.CreateDirectory(LayoutPath);
                }
                string StartOrdergvProductListPath = LayoutPath + "\\StartOrdergvProductList.Xml";
                string StartOrdergvProductPath = LayoutPath + "\\StartOrdergvProduct.Xml";

                if (File.Exists(StartOrdergvProductListPath))
                {
                    gvProductList.RestoreLayoutFromXml(StartOrdergvProductListPath);
                }
                if (File.Exists(StartOrdergvProductPath))
                {
                    gvProduct.RestoreLayoutFromXml(StartOrdergvProductPath);
                }
                //navBarGroupControlContainer2.AutoScroll = true;
                //navBarGroupControlContainer2.HorizontalScroll.Enabled = true;
                //navBarGroupControlContainer2.VerticalScroll.Enabled = true;
                spcProductDetail.Panel2.AutoScroll = true;
                //bcProductCommon.h
                bcProduct.ScrollMode = DevExpress.XtraNavBar.NavBarScrollMode.ScrollAlways;
;               
            }
            catch (Exception ex)
            {
                Cursor = Cursors.Default;
                if (ex is DataException) //断网
                {
                    MessageBox.Show(ConstString.StringCS.DataExceptionString, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    this.Close();
                }
                else
                {
                    MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
        }

        /// <summary>
        /// 设置开单目录树
        /// </summary>
        /// <param name="frm"></param>
        public static void SetStartOrderTree(FrmStartOrder frm)
        {
            if (IsGetTree == true && IsOpenStartOrder == true)
            {
                frm.lblTree.Visible = false;
                frm.Invoke(frm.InvokeSetStartOrderPath);
            }
        }

        //刷新待开单路径
        private void lblRefreshPath_Click(object sender, EventArgs e)
        {
            try
            {
                Cursor = Cursors.WaitCursor;
                //加载待开单目录树
                lblTree.Visible = false;
                GetTree();
                AddStartOrderPath2();
                Cursor = Cursors.Default;
            }
            catch (Exception ex)
            {
                Cursor = Cursors.Default;
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        #region 绑定打印机
        /// <summary>
        /// 绑定打印机
        /// </summary>
        private void BindPrinter()
        {
            try
            {
                cbPrinter.DisplayMember = "PrinterName";
                cbPrinter.ValueMember = "PrinterId";
                cbPrinter.DataSource = AllPrinter;
                cbPrinter.SelectedValue = 0;                //默认无打印机选中
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
        #endregion

        /// <summary>
        /// 设置Tcp连接
        /// </summary>
        private void SetTcpConnect()
        {
            TcpClient client = new TcpClient();
            try
            {
                //string server = Properties.Settings.Default.userCrcServer;
                string server = ConfigurationManager.AppSettings["RemoteIP"];
                int port = 9999;
                try
                {
                    port = Convert.ToInt32(ConfigurationManager.AppSettings["CrcPort"]);
                }
                catch
                {
                    port = 9999;
                }
                client.Connect(server, port);
                //client.Connect("192.168.1.104", 9999);
                clientSocket = client.Client;
            }
            catch (Exception exx)
            {
                if (exx is SocketException)
                {
                    SocketException se = exx as SocketException;
                    if (se.ErrorCode == 10061)
                    {
                        MessageBox.Show("照片重复验证服务端异常或服务未启动。如果要执行验证，请重启服务，再重启开单！", "确定", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                }
            }
        }
        /// <summary>
        /// 是否需要Crc验证
        /// </summary>
        private void SetCrc()
        {
            try
            {
                //cbPhotoRepeatCheck.Checked = Properties.Settings.Default.userCrc;
                cbPhotoRepeatCheck.Checked = ConfigurationManager.AppSettings["IsCheckCrcCode"] == "True" ? true : false;
                if (cbPhotoRepeatCheck.Checked)
                    IsNeedCheckPhotoRepeat = true;
                else
                    IsNeedCheckPhotoRepeat = false;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        #region 设置整体Form的样式
        /// <summary>
        /// 设置整体Form的样式
        /// </summary>
        private void SetFormStyle()
        {
            try
            {
                if (this.Width - 6 - spcBase.SplitterPosition > 300)
                {
                    spcBase.SplitterPosition = this.Width - 6 - 300;
                    if (spcBase.SplitterPosition - spcSecond.SplitterPosition > 200)
                    {
                        spcSecond.SplitterPosition = spcBase.SplitterPosition - 200;
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
        #endregion

        #region 设置常用产品的数量
        /// <summary>
        /// 设置常用产品的数量
        /// </summary>
        private void SetUsuallyUseNum()
        {
            try
            {
                int num = Properties.Settings.Default.UsuallyUseNum;
                this.txtUsuallyUse.Text = num.ToString();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
        #endregion

        #region 单击退出时间选择
        private void dtOrderTime_Properties_VistaTimeProperties_EditValueChanged(object sender, EventArgs e)
        {
            //dtOrderTime.ClosePopup();
        }

        private void dtFetchTime_Properties_VistaTimeProperties_EditValueChanged(object sender, EventArgs e)
        {
            //dtFetchTime.ClosePopup();
        }

        private void dtYJCompleteTime_Properties_VistaTimeProperties_EditValueChanged(object sender, EventArgs e)
        {
            //dtYJCompleteTime.ClosePopup();
        }
        #endregion

        #region 设置时间
        /// <summary>
        /// 设置时间
        /// </summary>
        private void SetTime()
        {
            dtOrderTime.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm");
            dtFetchTime.Text = DateTime.Now.ToString("yyyy-MM-dd");
            dtYJCompleteTime.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm");
        }
        #endregion

        #region 已设置取件时间标志(若没有设置，取件时间随预计完成时间变化；如果已设置取件时间，则即使预计完成时间发生变化，取件时间也不改变)
        private void dtFetchTime_QueryCloseUp(object sender, CancelEventArgs e)
        {
            IsSetFetchTime = true;
        }
        #endregion

        #region 设置订单包号
        /// <summary>
        /// 设置订单包号
        /// </summary>
        private void SetOrderBagCode()
        {
            btnCodeType.Text = btnCodeType.Text == "自动" ? "手动" : "自动";
            if (btnCodeType.Text == "手动")
            {
                txtOrderBagCode.Enabled = false;
                txtOrderBagCode.Text = BagCode;
            }
            else
            {
                txtOrderBagCode.Enabled = true;
                txtOrderBagCode.Text = "";
            }
        }
        #endregion

        #region "自动"，"手动"操作
        //"自动"，"手动"操作
        private void btnCodeType_Click(object sender, EventArgs e)
        {
            try
            {
                SetOrderBagCode();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
        #endregion

        #region 选择产品的操作

        #region 添加产品列表
        /// <summary>
        /// 添加产品列表
        /// </summary>
        /*private void AddProduct()
        {
            bcProduct.Groups.Clear();
            foreach (BLL.CustomerManage.StartOrderBLL.STProduct product in productList)
            {
                int productID = product.ProductID;
                int productCategoryID = product.ProductCategoryID;
                bool IsExistGroup = false;
                foreach (DevExpress.XtraNavBar.NavBarGroup g in bcProduct.Groups)
                {
                    if (Convert.ToInt16(g.Tag) == productCategoryID)
                    {
                        IsExistGroup = true;    //表示组已存在
                        //向组内添加元素
                        AddItemToProductGroup(product, g);
                        break;
                    }
                }
                if (IsExistGroup == false)  //如果组不存在，就添加
                {
                    DevExpress.XtraNavBar.NavBarGroup group = new DevExpress.XtraNavBar.NavBarGroup();
                    group.Caption = product.ProductCategoryName;
                    group.Tag = productCategoryID;
                    group.Expanded = false;
                    AddItemToProductGroup(product, group);
                    bcProduct.Groups.Add(group);
                }

            }
        }*/
        private void AddProduct(List<StartOrderBLL.STProductDisplay> srcList)
        {
           //bcProduct_ActiveGroupChanged
            //bcProduct.ActiveGroupChanged-=
                this.bcProduct.ActiveGroupChanged -= new DevExpress.XtraNavBar.NavBarGroupEventHandler(this.bcProduct_ActiveGroupChanged);
            //移除对Grid的引用
            foreach (DevExpress.XtraNavBar.NavBarGroup g in bcProduct.Groups)
            {
                if (g.ControlContainer != null && g.ControlContainer.Controls.Contains(gcProductCategory))
                {
                    g.ControlContainer.Controls.Remove(gcProductCategory);
                    break;
                }
            }
            bcProduct.Groups.Clear();
            foreach (StartOrderBLL.STProductDisplay product in srcList)
            {
                int productID = product.ProductID;
                int productCategoryID = product.ProductCategoryID;
                bool IsExistGroup = false;
                foreach (DevExpress.XtraNavBar.NavBarGroup g in bcProduct.Groups)
                {
                    if (Convert.ToInt16(g.Tag) == productCategoryID)
                    {
                        IsExistGroup = true;    //表示组已存在
                        break;
                    }
                }
                if (IsExistGroup == false)  //如果组不存在，就添加
                {
                    DevExpress.XtraNavBar.NavBarGroup group = new DevExpress.XtraNavBar.NavBarGroup();
                    group.Caption = product.ProductCategoryName;
                    group.Tag = productCategoryID;
                    group.Expanded = false;
                    //group.GroupStyle = NavBarGroupStyle.ControlContainer;
                    //group.ControlContainer = new NavBarGroupControlContainer();
                  
                    bcProduct.Groups.Add(group);
                       
                }
            }
            if (bcProduct.Groups != null && bcProduct.Groups.Count == 1)
            {
                DevExpress.XtraNavBar.NavBarGroup group = new DevExpress.XtraNavBar.NavBarGroup();
                group.Caption = "";
                group.Expanded = false;
                bcProduct.Groups.Add(group);
            }
            bcProduct.ScrollMode = DevExpress.XtraNavBar.NavBarScrollMode.ScrollAlways;
            this.bcProduct.ActiveGroupChanged += new DevExpress.XtraNavBar.NavBarGroupEventHandler(this.bcProduct_ActiveGroupChanged);
            //bcProduct_ActiveGroupChanged(null,bcProduct.Groups[0].)
        }
        #endregion 添加产品列表


        private int _shopPaperTypeID = 0;
        private string _shopPaperTypeName = "";
        private int _shopPaperFaceID = 0;
        private string _shopPaperFaceName = "";

        public int ShopPaperTypeID
        {
            get { return _shopPaperTypeID; }
            set
            {
                _shopPaperTypeID = value;
                if (ListProduct != null || ListProduct.Count < 1)
                {
                    ListProduct.ForEach(p => p.PaperTypeID = value);
                }

            }
            //get { return _shopPaperTypeID; }
            //set { _shopPaperTypeID = value; }
        }
        public string ShopPaperTypeName
        {
            get { return _shopPaperTypeName; }
            set
            {
                _shopPaperTypeName = value;
                cbPaperType.Text = value;
                if (ListProduct != null || ListProduct.Count < 1)
                {
                    ListProduct.ForEach(p => p.PaperTypeName = value);
                }
                //foreach (StartOrderBLL.STPaperType ptype in ListPaperType)
                //{
                //    if (value == ptype.PaperTypeName)
                //    {
                //        ShopPaperTypeID = ptype.PaperTypeID;
                //        break;
                //    }
                //}
                StartOrderBLL.STPaperType ptype = ListPaperType.FirstOrDefault(p => p.PaperTypeName == value);
                ShopPaperTypeID = ptype.PaperTypeID;

            }
        }
        public int ShopPaperFaceID
        {
            get { return _shopPaperFaceID; }
            set
            {
                _shopPaperFaceID = value;
                if (ListProduct != null || ListProduct.Count < 1)
                {
                    ListProduct.ForEach(p => p.PaperFaceID = value);
                }


            }
            //get { return _shopPaperFaceID; }
            //set
            //{
            //    _shopPaperFaceID = value;

            //}
        }
        public string ShopPaperFaceName
        {
            get { return _shopPaperFaceName; }
            set
            {
                _shopPaperFaceName = value;
                cbPaperFace.Text = (string)value;
                if (ListProduct != null || ListProduct.Count < 1)
                {
                    ListProduct.ForEach(p => p.PaperFaceName = value);
                }
                StartOrderBLL.STPaperFace face = ListPaperFace.FirstOrDefault(p => p.PaperFaceName == value);
                //ShopPaperTypeID = face.PaperFaceID;
                ShopPaperFaceID = face.PaperFaceID;

            }
        }


        #region 设置商户特有的产品分组
        //设置商户特有的产品分组
        private void cbShopName_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                string sname = this.cbShopName.Text;
                if (sname == lastShopName)
                    return;
                lastShopName = sname;
                xtraTabControl1.SelectedTabPage = xtraTabPage1;
                //获取商户特有的产品集合
                string shopName = cbShopName.Text;
                int shopId = 0;
                //foreach (StartOrderBLL.STShop s in ListShop)
                //{
                StartOrderBLL.STShop s = ListShop.FirstOrDefault(p => p.ShopName == shopName);
                AllCostItem = SOBLL.GetShopCostItems(s.ShopID);
                repositoryItemCheckedComboBoxEditCostType.Items.Clear();
                foreach (MINERP.MODEL.CustomerManage.StartOrder.CommonChargeItemDDO ddo in AllCostItem)
                {
                    repositoryItemCheckedComboBoxEditCostType.Items.Add(ddo.ItemName);
                }
                if (s.ShopName == shopName)
                {
                    shopId = s.ShopID;
                    CurrentShopId = shopId;
                    //商户的默认加急级别
                    cbPriority.Text = s.Priority.ToString();
                    //商户默认的纸型纸面
                    string pfaceName = "";
                    foreach (StartOrderBLL.STPaperFace f in ListPaperFace)
                    {

                        if (s.paperFaceId == f.PaperFaceID)
                        {
                            ShopPaperFaceID = f.PaperFaceID;
                            ShopPaperFaceName = f.PaperFaceName;

                            pfaceName = f.PaperFaceName;

                            break;
                        }
                    }
                    cbShopPaperFace.Text = pfaceName;
                    string ptypeName = "";
                    foreach (StartOrderBLL.STPaperType f in ListPaperType)
                    {
                        if (s.paperTypeId == f.PaperTypeID)
                        {
                            {
                                ShopPaperTypeID = f.PaperTypeID;
                                ShopPaperTypeName = f.PaperTypeName;
                                ptypeName = f.PaperTypeName;
                                break;
                            }
                        }
                    }
                    cbShopPaperType.Text = ptypeName;
                    //break;
                }
                //}

                //移除对Grid的引用
                foreach (DevExpress.XtraNavBar.NavBarGroup g in bcProductCommon.Groups)
                {
                    if (g.ControlContainer != null && g.ControlContainer.Controls.Contains(gcProductCategoryShop))
                    {
                        g.ControlContainer.Controls.Remove(gcProductCategoryShop);
                        break;
                    }
                }
                bcProductCommon.Groups.Clear();
                gcUsuallyUse.DataSource = null;
                if (shopId == 0)
                    return;
                productListShop = SOBLL.GetShopProductList(shopId);

                ListProductDisplayShop = new List<StartOrderBLL.STProductDisplay>();
                foreach (StartOrderBLL.ProductInfo s1 in productListShop)
                {
                    StartOrderBLL.STProductDisplay display = new StartOrderBLL.STProductDisplay();
                    display.ProductID = s1.ProductID;
                    display.ProductName = s1.ProductName;
                    display.ProductCategoryID = s1.ProductCategoryID;
                    display.ProductCategoryName = s1.ProductCategoryName;
                    float rh = s1.Height;
                    float rw = s1.Width;
                    display.ProductHW = string.Format("{0:0.##}", rh) + "×" + string.Format("{0:0.##}", rw);
                    display.ProductH = rh;
                    display.ProductW = rw;
                    display.ZJCode = s1.ZJCode;
                    display.UsedTimes = s1.UsedTimes;
                    ListProductDisplayShop.Add(display);
                }

                var groups = ListProductDisplayShop.GroupBy(p => p.ProductCategoryID);


                foreach (var group in groups)
                {
                    foreach (var item in group)
                    {
                        DevExpress.XtraNavBar.NavBarGroup g = new DevExpress.XtraNavBar.NavBarGroup();
                        g.Caption = item.ProductCategoryName;
                        g.Tag = item.ProductCategoryID;
                        bcProductCommon.Groups.Add(g);
                        break;
                    }
                }
                if (bcProductCommon.Groups != null && bcProductCommon.Groups.Count == 1)
                //if (bcProductCommon.Groups != null )                   
                {
                    DevExpress.XtraNavBar.NavBarGroup group = new DevExpress.XtraNavBar.NavBarGroup();
                    group.Caption = "";
                    group.Expanded = false;
                    bcProductCommon.Groups.Add(group);
                }
                xtraTabControl1.SelectedTabPage = xtraTabPage3;
                //cbShopPaperType.da
                cbPaperType.Properties.Items.Clear();
                repositoryItemComboBoxPaperType.Items.Clear();
                cbShopPaperType.Properties.Items.Clear();

                List<StartOrderBLL.STPaperType> listPaperType = SOBLL.GetShopPaperType(shopId);
                CurrShopPaperType = listPaperType;
                foreach (StartOrderBLL.STPaperType stPaperType in listPaperType)
                {
                    cbPaperType.Properties.Items.Add(stPaperType.PaperTypeName);
                    cbShopPaperType.Properties.Items.Add(stPaperType.PaperTypeName);
                    ((DevExpress.XtraEditors.Repository.RepositoryItemComboBox)repositoryItemComboBoxPaperType).Items.Add(stPaperType.PaperTypeName);
                    
                }
                //cbShopPaperType.SelectedIndex = 0;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
        #endregion

        //加载常用产品
        private void xtraTabControl1_SelectedPageChanged(object sender, DevExpress.XtraTab.TabPageChangedEventArgs e)
        {
            if (e.Page.Name == "xtraTabPage3")
            {
                AddUsuallyUseProducts();
            }
        }

        #region 加载常用产品
        /// <summary>
        /// 加载常用产品
        /// </summary>
        private void AddUsuallyUseProducts()
        {
            try
            {
                int num = Properties.Settings.Default.UsuallyUseNum;
                //加载常用产品
                if (ListProductDisplayShop == null)
                    return;
                ListProductDisplayUsually = ListProductDisplayShop.OrderByDescending(p => p.UsedTimes).ToList().GetRange(0, ListProductDisplayShop.Count > num ? num : ListProductDisplayShop.Count);
                foreach (DevExpress.XtraNavBar.NavBarGroup g in bcUsuallyUse.Groups)
                {
                    if (g.ControlContainer != null && g.ControlContainer.Controls.Contains(gcUsuallyUse))
                    {
                        g.ControlContainer.Controls.Remove(gcUsuallyUse);
                        break;
                    }
                }
                //if (gcUsuallyUse.Parent != null)
                //{
                //    gcUsuallyUse.Parent.Controls.Remove(gcUsuallyUse);
                //}
                bcUsuallyUse.Groups.Clear();
                var uGroups = ListProductDisplayUsually.GroupBy(p => p.ProductCategoryID);
                foreach (var g in uGroups)
                {
                    DevExpress.XtraNavBar.NavBarGroup ng = new DevExpress.XtraNavBar.NavBarGroup();
                    ng.Caption = g.First().ProductCategoryName;
                    ng.Tag = g.First().ProductCategoryID;
                    bcUsuallyUse.Groups.Add(ng);
                }
                if (bcUsuallyUse.Groups != null && bcUsuallyUse.Groups.Count == 1)
                {
                    DevExpress.XtraNavBar.NavBarGroup group = new DevExpress.XtraNavBar.NavBarGroup();
                    group.Caption = "";
                    group.Expanded = false;
                    bcUsuallyUse.Groups.Add(group);
                }
                gcUsuallyUse.RefreshDataSource();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region 向产品列表组内添加产品
        /// <summary>
        /// 向产品列表组内添加产品
        /// </summary>
        //所有的产品
        private void bcProduct_ActiveGroupChanged(object sender, DevExpress.XtraNavBar.NavBarGroupEventArgs e)
        {
            try
            {
                e.Group.GroupStyle = DevExpress.XtraNavBar.NavBarGroupStyle.ControlContainer;
                DevExpress.XtraGrid.GridControl grid = gcProductCategory ;
                grid.Visible = true;
                FilterDisplayProduct.Clear();       //清除上一类别的信息
                int productCategoryID = Convert.ToInt16(e.Group.Tag);
                //foreach (StartOrderBLL.STProductDisplay product in ListProductDisplay)
                foreach (StartOrderBLL.STProductDisplay product in SXList)
                {
                    if (product.ProductCategoryID == productCategoryID)
                    {
                        FilterDisplayProduct.Add(product);
                    }
                }
                grid.DataSource = FilterDisplayProduct;
                grid.RefreshDataSource();
                grid.Dock = DockStyle.Fill;
                e.Group.ControlContainer.Controls.Add(grid);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
        //商户特有的产品
        private void bcProductCommon_ActiveGroupChanged(object sender, DevExpress.XtraNavBar.NavBarGroupEventArgs e)
        {
            try
            {
                e.Group.GroupStyle = DevExpress.XtraNavBar.NavBarGroupStyle.ControlContainer;
                //e.Group.Appearance.s
                DevExpress.XtraGrid.GridControl grid = gcProductCategoryShop;
                grid.Visible = true;
                FilterDisplayProductShop.Clear();
                int productCategoryID = Convert.ToInt16(e.Group.Tag);
                foreach (StartOrderBLL.STProductDisplay product in ListProductDisplayShop)
                {
                    if (product.ProductCategoryID == productCategoryID)
                    {
                        FilterDisplayProductShop.Add(product);
                    }
                }
                grid.DataSource = FilterDisplayProductShop;
                grid.RefreshDataSource();
                grid.Dock = DockStyle.Fill;
                
                e.Group.ControlContainer.Controls.Add(grid);
                e.Group.ControlContainer.AutoScroll = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
        //常用产品
        private void bcUsuallyUse_ActiveGroupChanged(object sender, DevExpress.XtraNavBar.NavBarGroupEventArgs e)
        {
            try
            {
                e.Group.GroupStyle = DevExpress.XtraNavBar.NavBarGroupStyle.ControlContainer;
                gcUsuallyUse.Visible = true;
                FilterUsually.Clear();
                int categoryId = Convert.ToInt32(e.Group.Tag);
                foreach (StartOrderBLL.STProductDisplay p in ListProductDisplayUsually)
                {
                    if (p.ProductCategoryID == categoryId)
                        FilterUsually.Add(p);
                }
                gcUsuallyUse.Dock = DockStyle.Fill;
                gcUsuallyUse.DataSource = FilterUsually;
                gcUsuallyUse.RefreshDataSource();
                e.Group.ControlContainer.Controls.Add(gcUsuallyUse);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
        #endregion

        #region 展开某类产品时，其他类型的产品都关闭
        private void bcProduct_GroupExpanded(object sender, DevExpress.XtraNavBar.NavBarGroupEventArgs e)
        {
            foreach (DevExpress.XtraNavBar.NavBarGroup g in bcProduct.Groups)
            {
                if (e.Group != g)
                {
                    g.Expanded = false;
                }
            }
        }
        #endregion

        #endregion

        #region 产品开始拖曳
        private void bcProduct_LinkPressed(object sender, DevExpress.XtraNavBar.NavBarLinkEventArgs e)
        {
            try
            {
                string xx = e.Link.Item.Tag.ToString();
                DataObject data = new DataObject(DataFormats.StringFormat, xx);
                DoDragDrop(data, DragDropEffects.All);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
        //gridControls拖曳
        GridHitInfo downHitInfo = null;
        private void gvProductCategory_MouseDown(object sender, MouseEventArgs e)
        {
            try
            {
                downHitInfo = null;
                GridView view = sender as GridView;
                GridHitInfo hitInfo = view.CalcHitInfo(e.X, e.Y);
                if (Control.ModifierKeys != Keys.None) return;
                if (e.Button == MouseButtons.Left && hitInfo.InRow && hitInfo.HitTest != GridHitTest.RowIndicator)
                    downHitInfo = hitInfo;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        private void gvProductCategory_MouseMove(object sender, MouseEventArgs e)
        {
            try
            {
                GridView view = sender as GridView;
                if (e.Button == MouseButtons.Left && downHitInfo != null)
                {
                    Size dragSize = SystemInformation.DragSize;
                    Rectangle dragRect = new Rectangle(new Point(downHitInfo.HitPoint.X - dragSize.Width / 2,
                        downHitInfo.HitPoint.Y - dragSize.Height / 2), dragSize);
                    if (!dragRect.Contains(new Point(e.X, e.Y)))
                    {
                        int[] rows = view.GetSelectedRows();

                        if (rows.Length > 0)
                        {
                            if (!view.IsGroupRow(rows[0]))
                            {
                                DragType = 3;                                               //产品模板
                                StartOrderBLL.STProductDisplay product = (StartOrderBLL.STProductDisplay)view.GetRow(rows[0]);
                                int pid = product.ProductID;
                                List<string> pids = new List<string>();
                                pids.Add(pid.ToString());
                                DataObject data = new DataObject();
                                data.SetData("list", pids);
                                DoDragDrop(data, DragDropEffects.All);
                                downHitInfo = null;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
        #endregion

        //常用产品的拖曳操作
        private void gvUsuallyUse_MouseDown(object sender, MouseEventArgs e)
        {
            try
            {
                downHitInfo = null;
                GridView view = sender as GridView;
                GridHitInfo hitInfo = view.CalcHitInfo(e.X, e.Y);
                if (ModifierKeys != Keys.None) return;
                if (e.Button == MouseButtons.Left && hitInfo.InRow && hitInfo.HitTest != GridHitTest.RowIndicator)
                    downHitInfo = hitInfo;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        private void gvUsuallyUse_MouseMove(object sender, MouseEventArgs e)
        {
            try
            {
                GridView view = sender as GridView;
                if (e.Button == MouseButtons.Left && downHitInfo != null)
                {
                    System.Drawing.Size dragSize = SystemInformation.DragSize;
                    Rectangle rec = new Rectangle(new Point(downHitInfo.HitPoint.X - dragSize.Width / 2, downHitInfo.HitPoint.Y - dragSize.Height / 2), dragSize);
                    if (!rec.Contains(e.X, e.Y))
                    {
                        int[] rows = view.GetSelectedRows();

                        if (rows.Length > 0)
                        {
                            if (!view.IsGroupRow(rows[0]))
                            {
                                DragType = 3;                                               //产品模板
                                StartOrderBLL.STProductDisplay product = (StartOrderBLL.STProductDisplay)view.GetRow(rows[0]);
                                int pid = product.ProductID;
                                List<string> pids = new List<string>();
                                pids.Add(pid.ToString());
                                DataObject data = new DataObject();
                                data.SetData("list", pids);
                                DoDragDrop(data, DragDropEffects.All);
                                downHitInfo = null;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        #region 向产品列表拖入产品实体
        //向产品列表拖入产品
        bool IsAddedScroll = false; //表示流程panel是否已加了scroll
        private void gcProductList_DragEnter(object sender, DragEventArgs e)
        {
            try
            {
                if (e.Data.GetDataPresent("list"))
                {
                    e.Effect = DragDropEffects.All;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        //高亮显示鼠标所在行
        private void gcProductList_DragOver(object sender, DragEventArgs e)
        {
            try
            {
                Point p1 = gcProductList.PointToClient(new Point(e.X, e.Y));                //
                DevExpress.XtraGrid.Views.Grid.ViewInfo.GridHitInfo info = gvProductList.CalcHitInfo(p1);
                if (info.InRow)
                {
                    gvProductList.FocusedRowHandle = info.RowHandle;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        private void gcProductList_DragDrop(object sender, DragEventArgs e)
        {
            try
            {
                //取消键盘上下键移动获取焦点事件
                gvProductList.FocusedRowChanged -= gvProductList_FocusedRowChanged;
                if (e.Data.GetDataPresent("list"))
                {
                    Point p1 = gcProductList.PointToClient(new Point(e.X, e.Y));                //
                    DevExpress.XtraGrid.Views.Grid.ViewInfo.GridHitInfo info = gvProductList.CalcHitInfo(p1);
                    if (ListProduct.Count == 0 || !info.InRow)
                    {
                        currentProduct = null;
                    }
                    else
                    {
                        StartOrderBLL.ProductInfo product = gvProductList.GetRow(info.RowHandle) as StartOrderBLL.ProductInfo;
                        int serialID = product.ProductSerialID;
                        isAddOldTech = true;                                                //表示是已添加的产品
                        SetProductDetail(serialID);
                    }
                    if (DragType == 3)                                      //拖曳的类型 1客户实体 2产品实体 3产品模板 4客户目录的产品实体
                    {
                        List<string> pids = e.Data.GetData("list") as List<string>;
                        int pid = Convert.ToInt16(pids[0]);
                        if (currentProduct == null)                         //新增产品模板
                        {
                            //产品的使用次数加1
                            SOBLL.ProductUseTimeAdd(pid, CurrentShopId);
                            //保存上个产品明细
                            SaveCurrentProduct();
                            IsNewProduct = true;                            //表示是新产品
                            isAddOldTech = false;                           //表示是还未添加的产品
                            //执行清理操作
                            ClearProductDetail();
                            AcceptData(pid);
                        }
                        else if (currentProduct != null && currentProduct.ProductType == 1)
                        {
                            //产品的使用次数加1
                            SOBLL.ProductUseTimeAdd(pid, CurrentShopId);
                            //保存上个产品明细
                            SaveCurrentProduct();
                            //模板匹配实体
                            isAddOldTech = false;
                            AddModelForProduct(pid);
                            SetPhotoProperty(true);     //根据ProductTypeCode设置照片属性,需要指定默认尺寸
                        }
                        else
                        {
                            MessageBox.Show("产品模板已添加!", "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                            return;
                        }
                    }
                    else if (DragType == 1)                                 //客户实体
                    {
                        List<string> productPaths = e.Data.GetData("list") as List<string>;
                        if (currentProduct == null)             //新增产品实体
                        {
                            foreach (string productPath in productPaths)
                            {
                                //保存上个产品明细
                                SaveCurrentProduct();
                                IsNewProduct = true;
                                AddNewProductEntity(productPath);
                                // SetPhotoNumAndArea("3");//新增照片时计算照片的尺寸
                            }
                        }
                        else if (currentProduct != null && productPaths.Count == 1 && currentProduct.ProductType == 2)  //1实体  2产品模板  3二者综合
                        {
                            //保存上个产品明细
                            SaveCurrentProduct();
                            //将实体匹配模板
                            string productPath = productPaths[0];
                            AddProductOnModel(productPath);
                            SetPhotoProperty(true);//根据ProductTypeCode设置照片属性,需要指定默认尺寸
                        }
                        else                                    //产品实体和模板不匹配
                        {
                            MessageBox.Show("无法添加产品!", "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                            return;
                        }
                        //设置已开单节点背景色
                        foreach (TreeNode n in currentNode.Nodes)
                        {
                            n.BackColor = Color.Pink;
                        }
                        currentNode.BackColor = Color.Pink;
                    }
                    else if (DragType == 2 || DragType == 4)                                                 //产品实体(客户目录指定的产品实体)
                    {
                        List<string> productPaths = e.Data.GetData("list") as List<string>;
                        string productPath = productPaths[0];
                        if (DragType == 4)
                        {
                            string[] files = GetFilesPath(productPath);
                            string[] directorys = Directory.GetDirectories(productPath);
                            if (files.Length > 0 && directorys.Length > 0)
                            {
                                DirectoryInfo dinfo = new DirectoryInfo(productPath);
                                if (MessageBox.Show("“" + dinfo.Name + "” 内有照片和目录同时存在，要继续开单吗?", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.No)
                                    return;
                            }
                        }
                        if (currentProduct == null)
                        {
                            //保存上个产品明细
                            SaveCurrentProduct();
                            //新增产品实体
                            IsNewProduct = true;
                            AddNewProductEntity(productPath);
                        }
                        else if (currentProduct != null && currentProduct.ProductType == 2)                      //1实体  2产品模板  3二者综合
                        {
                            //保存上个产品明细
                            SaveCurrentProduct();
                            //将实体匹配模板
                            AddProductOnModel(productPath);
                            SetPhotoProperty(true);//根据ProductTypeCode设置照片属性,需要指定默认尺寸
                        }
                        else
                        {
                            MessageBox.Show("无法添加产品!", "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                            return;
                        }
                        //设置已开单节点背景色
                        currentNode.BackColor = Color.Pink;
                    }
                    gcProductList.RefreshDataSource();
                    //加上键盘上下键移动获取焦点事件
                    gvProductList.FocusedRowChanged += gvProductList_FocusedRowChanged;
                }
            }
            catch (RasterException ex)
            {
                MessageBox.Show(RasterException.GetCodeMessage(ex.Code));
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
        /// <summary>
        /// 接收产品操作
        /// </summary>
        /// <param name="productID"></param>
        private void AcceptData(int productID)
        {
            for (int i = 0; i < productListShop.Count; i++)
            {
                if (productListShop[i].ProductID == productID)
                {

                    //其余信息在添加产品时设置

                    StartOrderBLL.ProductInfo newProduct = new StartOrderBLL.ProductInfo();
                    newProduct = AddModelCommonPara(productListShop[i], newProduct);
                    newProduct.CtmName = "";
                    newProduct.ProductSerialID = currentSerialID;
                    newProduct.ProductType = 2;                                         //1实物  2产品模板  3二者综合
                    newProduct.Unit = cbUnit.Text.Trim();
                    newProduct.Photos = new List<StartOrderBLL.STPhoto>();
                    //ProductDataSource.Add(newProduct);
                    ListProduct.Add(newProduct);
                    //最新的新增行获得焦点
                    SetProductListFocusRow(currentSerialID);
                    currentProduct = newProduct;

                    //设置当前产品照片的数据源
                    gcProduct.DataSource = newProduct.Photos;

                    //设置照片数量与总面积
                    SetPhotoNumAndArea(currentProduct.ProductTypeCode);


                    //新增产品系列增1
                    currentSerialID++;

                    //计算当前产品的预计用时
                    ComputeProductHours();

                    gcProductList.RefreshDataSource();
                    break;
                }
            }
        }
        #endregion

        #region 加载模板的公共参数
        /// <summary>
        /// 加载模板的公共参数
        /// </summary>
        /// <param name="modelProduct">产品模板</param>
        /// <param name="entityProduct">产品实体</param>
        private StartOrderBLL.ProductInfo AddModelCommonPara(StartOrderBLL.ProductInfo modelProduct, StartOrderBLL.ProductInfo entityProduct)
        {
            cbPaperType.Text = entityProduct.PaperTypeName;
            //cbPaperType.Text = cbShopPaperType.Text;
            cbPaperFace.Text = entityProduct.PaperFaceName;
            //cbPaperFace.Text = cbShopPaperFace.Text;
            SetEnableAndDisable(modelProduct.ProductTypeCode);                   //设置可用与不可用，可见与不可见
            float rh = modelProduct.Height;                                   //产品的真实高宽(用英寸表示)
            float rw = modelProduct.Width;
            float maxRh = rh * (float)1.1;
            float minRh = rh * (float)0.9;
            float maxRw = rw * (float)1.1;
            float minRw = rw * (float)0.9;
            if (modelProduct.ProductTypeCode == 1 || modelProduct.ProductTypeCode == 2)     //实质是ProductTypeCode
            {
                float h = 0, w = 0;
                string unit = cbUnit.Text;
                switch (unit)
                {
                    case "厘米(cm)":
                        h = rh * (float)2.54;
                        w = rw * (float)2.54;
                        break;
                    case "英寸(in)":
                        h = rh;
                        w = rw;
                        break;
                    case "米(m)":
                        h = rh * (float)2.54 / 100;
                        w = rw * (float)2.54 / 100;
                        break;
                    case "毫米(mm)":
                        h = rh * (float)2.54 * 10;
                        w = rw * (float)2.54 * 10;
                        break;
                }
                //设置高宽的可变范围
                //SetMaxAndMin(h, w);
                //spinPageNum.Text = modelProduct.PageNum.ToString();
                spinHeight.Text = string.Format("{0:0.##}", h);
                spinWidth.Text = string.Format("{0:0.##}", w);
            }
            else
            {
                //spinPageNum.Text = "0";                       //P数等于照片数量
                spinHeight.Text = "0";
                spinWidth.Text = "0";
            }
            spinHeight.Tag = rh;
            spinWidth.Tag = rw;

            //加载产品默认流程
            singleProductTech = new List<StartOrderBLL.STProductTech>();        //保存当前产品默认流程
            List<StartOrderBLL.STProductTech> TempTechs = SOBLL.GetDefaultTechsOfProduct(modelProduct.ProductID);

            //商户每个节点的默认员工
            int shopID = 0;
            List<StartOrderBLL.STShop> ListShop = SOBLL.ListShop;
            foreach (StartOrderBLL.STShop s in ListShop)
            {
                if (s.ShopName == cbShopName.Text.Trim())
                {
                    shopID = s.ShopID;
                    break;
                }
            }
            if (Stu.FindAll(p => p.ShopId == shopID).Count == 0)         //表示还未加载商户，节点，员工
            {
                Stu.AddRange(SOBLL.GetShopTechUser(shopID));
            }
            List<MODEL.CustomerManage.StartOrder.ShopTechUser> filterStu = Stu.FindAll(p => p.ShopId == shopID);
            foreach (StartOrderBLL.STProductTech tech in TempTechs)
            {

                //节点默认的操作员
                foreach (MODEL.CustomerManage.StartOrder.ShopTechUser s in filterStu)
                {
                    if (s.TechId == tech.TechID)
                    {
                        tech.UserId = s.UserId;
                        break;
                    }
                }
                //委外流程默认的委外商
                if (tech.Techtype == (int)TechType.OutProduct)
                {
                    //先判断当前产品是否已加载了委外商
                    if (Po.Find(p => p.ProductId == modelProduct.ProductID) == null)                //表示还未从数据库取得产品所有的委外商
                    {
                        Po.AddRange(SOBLL.GetProductOutShop(modelProduct.ProductID));
                    }
                    MODEL.CustomerManage.StartOrder.ProductOutShop nullPo = new MINERP.MODEL.CustomerManage.StartOrder.ProductOutShop();    //空委外商，即在开单时可以不指定委外商
                    nullPo.ProductId = modelProduct.ProductID;
                    nullPo.OutShopId = 0;
                    nullPo.OutShopName = "无";

                    List<MINERP.MODEL.CustomerManage.StartOrder.ProductOutShop> filterPo = new List<MINERP.MODEL.CustomerManage.StartOrder.ProductOutShop>();
                    filterPo.Add(nullPo);               //将空委外商加入
                    filterPo.AddRange(Po.FindAll(p => p.ProductId == modelProduct.ProductID));
                    foreach (MODEL.CustomerManage.StartOrder.ProductOutShop p in filterPo)
                    {
                        if (p.IsDefaultOutShop == true)         //默认委外商
                        {
                            tech.OutShopId = p.OutShopId;
                            break;
                        }
                    }
                    tech.Pos = filterPo;                //当前产品所有可用的委外商
                }
                tech.IsNeed = true;
                singleProductTech.Add(tech);
            }
            foreach (StartOrderBLL.STProductTech stt in CommonProductTechBeforePrint)
            {
                StartOrderBLL.STProductTech sttTemp = singleProductTech.FirstOrDefault(p => p.TechID == stt.TechID);
                if (sttTemp == null)
                {
                    stt.IsNeed = false;
                    //stt.
                    singleProductTech.Add(stt);
                }
            }
            //TempTechs = TempTechs.OrderBy(p => p.WorkOrder).ToList();
            singleProductTech.Sort(StartOrderBLL.CompareTech);
            AddProductFlow(singleProductTech);
            entityProduct.techs = singleProductTech;
            entityProduct.Height = modelProduct.Height;
            entityProduct.ProductModel = new StartOrderBLL.ProductModel() { Productid = modelProduct.ProductID, Height = modelProduct.Height, Width = modelProduct.Width, PageNum = modelProduct.PageNum, ProductName = modelProduct.ProductName };
            //entityProduct.PageNum = modelProduct.PageNum;
            //entityProduct.PaperTypeID = modelProduct.PaperTypeID;
            //entityProduct.PaperFaceID = modelProduct.PaperFaceID;
            //entityProduct.PaperFaceName = modelProduct.PaperFaceName;
            //entityProduct.PaperTypeName = modelProduct.PaperTypeName;
            //根据商户信息获取纸型、纸面
            //int pfaceId = 0;
            //foreach (StartOrderBLL.STPaperFace face in ListPaperFace)
            //{
            //    if (face.PaperFaceName == cbShopPaperFace.Text)
            //    {
            //        pfaceId = face.PaperFaceID;
            //        break;
            //    }
            //}
            int pfaceId = 0;
            foreach (StartOrderBLL.STPaperFace face in ListPaperFace)//纸型纸面都用商户默认滴
            {
                if (face.PaperFaceName == cbPaperFace.Text)
                {
                    pfaceId = face.PaperFaceID;
                    break;
                }
            }
            entityProduct.PaperFaceID = pfaceId;
            entityProduct.PaperFaceName = cbShopPaperFace.Text;
            //entityProduct.PaperFaceID = modelProduct.PaperFaceID;
            //entityProduct.PaperFaceName = modelProduct.PaperFaceName;
            //MINERP.BLL.CustomerManage.StartOrderBLL.STPaperFace currFce= ListPaperFace.FirstOrDefault(p => p.PaperFaceID == modelProduct.PaperFaceID);
            //cbPaperFace.SelectedItem = currFce;
            //cbPaperFace.Text = modelProduct.PaperFaceName;
            int ptypeId = 0;
            string ptName="";
            //foreach (StartOrderBLL.STPaperType type in ListPaperType)
            //{
            //    if (type.PaperTypeName == modelProduct.PaperTypeName)
            //    {
            //        ptypeId = type.PaperTypeID;
            //        ptName = type.PaperTypeName;
            //        break;
            //    }
            //}
            StartOrderBLL.STPaperType stp = ListPaperType.FirstOrDefault(pt => pt.PaperTypeName == cbShopPaperType.Text);
            if (stp.PaperTypeID != 0)
            {
                entityProduct.PaperTypeID = stp.PaperTypeID;
                entityProduct.PaperTypeName = stp.PaperTypeName;
                cbPaperType.Text = stp.PaperTypeName;
            }
            
            
            


            entityProduct.ProductCategoryID = modelProduct.ProductCategoryID;
            entityProduct.ProductCategoryName = modelProduct.ProductCategoryName;
            entityProduct.ProductID = modelProduct.ProductID;
            if (entityProduct.ProductName != null && entityProduct.ProductName.Length > 0)
                entityProduct.ProductName = entityProduct.ProductName + "_" + modelProduct.ProductName; //产品名称由两部分组成
            else
                entityProduct.ProductName = modelProduct.ProductName;
            //entityProduct.ProductNum = 1;                                       //产品数量默认是1
            entityProduct.ProductNum = Convert.ToInt32(spinProductNum.Text);
            entityProduct.Width = modelProduct.Width;
            entityProduct.ProductTypeCode = modelProduct.ProductTypeCode;   //产品类型
            //spinProductNum.Text = "1";
            txtProductName.Text = entityProduct.ProductName;
            txtProductRemark.Text += "\\" + txtShopRequire.Text;
            entityProduct.ProductRemark = txtProductRemark.Text;
            //默认打印机
            cbPrinter.SelectedValue = SOBLL.GetProductPrinter(modelProduct.ProductID);
            //MINERP.BLL.CustomerManage.StartOrderBLL.STProductTech stTech = singleProductTech.FirstOrDefault(p => p.IsDesign);
            if (entityProduct.ProductTypeCode == (int)OrderInfoProductType.NeedDesignPrint || entityProduct.ProductTypeCode == (int)OrderInfoProductType.NeedDesignProduct || entityProduct.ProductTypeCode == (int)(int)OrderInfoProductType.NeedDesignKuoYin)
            {
                if (!entityProduct.IsCheckStyle)
                {


                    CheckSizeAndPage(entityProduct);

                }
            }
            int intPageNum = Convert.ToInt32(spinPageNum.Text.Trim());
            if (entityProduct.Photos != null && intPageNum > entityProduct.Photos.Count && !(entityProduct.ProductTypeCode == (int)OrderInfoProductType.NeedDesignPrint || entityProduct.ProductTypeCode == (int)OrderInfoProductType.NeedDesignProduct || entityProduct.ProductTypeCode == (int)OrderInfoProductType.NeedDesignKuoYin))
            {
                spinPageNum.Text = entityProduct.Photos.Count.ToString();
            }
            else
            {

            }
            // DisplayByUnit("厘米(cm)");
            cbUnit.Text = "厘米(cm)";
            foreach (MINERP.BLL.CustomerManage.StartOrderBLL.STProductTech Tech in singleProductTech)
            {
                if (!string.IsNullOrEmpty(Tech.CommonChargeItems))
                {
                    if (Tech.IsNeed)
                    {
                        entityProduct.StringCostItems += Tech.CommonChargeItems + ",";
                    }
                }

            }
            ///将产品的 附加收费自动带入
            foreach (ProductCommonItem item in modelProduct.ProductCommonBing)
            {
                if (AllCostItem.FirstOrDefault(p => p.CommonChargeItemId == item.CommonID) != null)
                {
                    entityProduct.StringCostItems += item.ItemName + ",";
                }

            }
            if (!string.IsNullOrEmpty(entityProduct.StringCostItems))
            {
                entityProduct.StringCostItems = entityProduct.StringCostItems.Trim(',');
            }
            return entityProduct;
        }
        #endregion

        #region 设置当前产品照片的属性
        /// <summary>
        /// 设置当前产品照片的属性
        /// </summary>
        private void SetPhotoProperty(bool isNeedCC)
        {
            if (currentProduct.ProductTypeCode == 2)    //不需要设计的产品(判断照片尺寸是否与产品匹配,注意照片的宽应与产品宽的2倍匹配)
            {
                float w = currentProduct.Width * 2;
                float h = currentProduct.Height;
                float maxW = w * (float)1.1;
                float minW = w * (float)0.9;
                float maxH = h * (float)1.1;
                float minH = h * (float)0.9;
                for (int i = 0; i < gvProduct.RowCount; i++)
                {
                    StartOrderBLL.STPhoto photo = gvProduct.GetRow(i) as StartOrderBLL.STPhoto;
                    float ph = photo.PhotoStandardHCompute;
                    float pw = photo.PhotoStandardWCompute;
                    //高宽有可能倒换
                    if ((ph <= maxH && ph >= minH && pw <= maxW && pw >= minW) || (ph <= maxW && ph >= minW && pw <= maxH && pw >= minH))
                    {
                        photo.IsPiPei = true;
                    }
                    else
                    {
                        photo.IsPiPei = false;
                    }
                    if (photo.PhotoDPI < 72)
                    {
                        photo.IsPiPei = false;
                    }
                }
            }
            //else if (currentProduct.productTypeRemark == "3" && isNeedCC == true)   //需要指定尺寸的扩印(照片默认尺寸等于产品尺寸，每张照片尺寸可单独修改)
            //{
            //    float h = currentProduct.Height;
            //    float w = currentProduct.Width;
            //    for (int i = 0; i < gvProduct.RowCount; i++)
            //    {
            //        StartOrderBLL.STPhoto photo = gvProduct.GetRow(i) as StartOrderBLL.STPhoto;
            //        if (photo.PhotoStandardHCompute != h && photo.PhotoStandardWCompute != w)
            //        {
            //            //照片标准高宽，用于计算
            //            photo.PhotoStandardHCompute = h;
            //            photo.PhotoStandardWCompute = w;
            //            //标准高宽，用于显示
            //            string standardHW = string.Format("{0:0.####}", h) + "×" + string.Format("{0:0.####}", w);
            //            photo.PhotoHWStandard = standardHW;
            //            //标准面积
            //            string standardArea = string.Format("{0:0.####}", h * w);
            //            photo.PhotoAreaStandard = standardArea;
            //            DisplayHWByUnit(photo);
            //        }
            //    }
            //}
        }
        #endregion

        #region 设置产品高宽的可变范围
        /// <summary>
        /// 设置高、宽的范围
        /// </summary>
        //private void SetMaxAndMin(float h, float w)
        //{
        //    float maxH = h * (float)1.1;
        //    float minH = h * (float)0.9;
        //    float maxW = w * (float)1.1;
        //    float minW = w * (float)0.9;
        //    spinHeight.Properties.MaxValue = (decimal)maxH;
        //    spinHeight.Properties.MinValue = (decimal)minH;
        //    spinWidth.Properties.MaxValue = (decimal)maxW;
        //    spinWidth.Properties.MinValue = (decimal)minW;
        //}
        #endregion

        #region 当前产品是非设计产品时，设置不匹配照片的背景色
        /// <summary>
        /// 照片不匹配产品时，设置照片的背景色
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void gvProduct_RowStyle(object sender, RowStyleEventArgs e)
        {
            try
            {
                if (currentProduct != null && currentProduct.Photos != null)
                {
                    StartOrderBLL.STPhoto photo = gvProduct.GetRow(e.RowHandle) as StartOrderBLL.STPhoto;
                    if (photo != null && photo.IsInDirectory == true)           //在选中的目录之中
                    {
                        e.Appearance.BackColor = Color.Green;
                        e.Appearance.BackColor2 = Color.Green;
                    }
                    else if (photo != null && photo.IsInDirectory == false && photo.IsPiPei == false)       //不在选中的目录之中，且尺寸不匹配
                    {
                        e.Appearance.BackColor2 = Color.Pink;
                        e.Appearance.BackColor2 = Color.Pink;
                    }
                    else
                    {
                        e.Appearance.BackColor2 = Color.Empty;
                        e.Appearance.BackColor2 = Color.Empty;
                    }
                    if (currentProduct.ProductTypeCode == 2 && photo != null && photo.IsPiPei == false)
                    {
                        e.Appearance.BackColor = Color.Pink;
                        e.Appearance.BackColor2 = Color.Pink;
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
        #endregion

        #region 新增时设置背景色
        private void gvProductList_RowStyle(object sender, RowStyleEventArgs e)
        {
            try
            {
                StartOrderBLL.ProductInfo product = gvProductList.GetRow(e.RowHandle) as StartOrderBLL.ProductInfo;
                if (product != null)
                {
                    if (product.ProductType != 3)
                    {

                        e.Appearance.BackColor = Color.Pink;
                        e.Appearance.BackColor2 = Color.Pink;
                    }
                    else if (product.ProductType == 3)
                    {
                        //gvProductList.Appearance.SelectedRow.BackColor = Color.White;
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
        #endregion

        #region 设置焦点
        private void SetProductListFocusRow(int rowHandle)
        {
            for (int i = 0; i < ListProduct.Count; i++)
            {
                StartOrderBLL.ProductInfo product = gvProductList.GetRow(i) as StartOrderBLL.ProductInfo;
                if (rowHandle == product.ProductSerialID)
                {
                    gvProductList.FocusedRowHandle = i;
                    return;
                }
            }
        }
        #endregion

        #region 设置字段显示顺序(当照片信息按设计类产品显示时)
        /// <summary>
        /// 设置字段显示顺序(当照片信息按设计类产品显示时)
        /// </summary>
        private void SetDisplayOrder()
        {
            gvProduct.Columns["PhotoHWStandard"].VisibleIndex = 3;
            gvProduct.Columns["PhotoAreaStandard"].VisibleIndex = 4;
            gvProduct.Columns["PhotoHW"].VisibleIndex = 5;
            gvProduct.Columns["PhotoArea"].VisibleIndex = 6;
            gvProduct.Columns["PhotoRemark"].VisibleIndex = 7;
        }
        #endregion

        /// <summary>
        /// 是否可设计，设置可用与不可用，可见与不可见
        /// </summary>
        private void SetEnableAndDisable(int productTypeCode)
        {
            ceProductWithoutPhotoClick = false;//非鼠标点击
            ceProductOutReturnClick = false;
            switch (productTypeCode)
            {
                case (int)OrderInfoProductType.NeedDesignProduct:                           //1 需要设计的产品和扩印产品，开单时不可输入尺寸，可以输入P数
                case (int)OrderInfoProductType.NeedDesignKuoYin:
                    spinHeight.Enabled = false;
                    spinWidth.Enabled = false;
                    spinPageNum.Enabled = true;
                    tsModifyPhotoHW.Visible = false;
                    //ceProductWithoutPhoto.Enabled = false;
                    ceProductWithoutPhoto.Checked = false;
                    break;
                case (int)OrderInfoProductType.NoNeedDesignProduct:                           //2 不需要设计的做相册
                case (int)OrderInfoProductType.NoNeedDesignPrint:                             // 不需要设计直出
                case (int)OrderInfoProductType.NoNeedDesignKuoYin:                             // 不需要设计扩印
                    spinHeight.Enabled = false;
                    spinWidth.Enabled = false;
                    spinPageNum.Enabled = false;
                    //tsModifyPhotoHW.Visible = false;
                    ceProductWithoutPhoto.Checked = false;
                    break;
                //case 3:                           //3 需要指定尺寸的扩印，所有照片的尺寸默认等于产品的尺寸，但每张照片可单独修改尺寸，保存也是照片本身的尺寸
                //    spinHeight.Enabled = false;
                //    spinWidth.Enabled = false;
                //    spinPageNum.Enabled = false;
                //    tsModifyPhotoHW.Visible = true;
                //    break;
                //case 4:                           //4 直接扩印，产品本身无尺寸，每张照片的尺寸按其本身的DPI计算，且照片尺寸不可修改
                //    spinHeight.Enabled = false;
                //    spinWidth.Enabled = false;
                //    spinPageNum.Enabled = false;
                //    tsModifyPhotoHW.Visible = false;
                //    break;
                case (int)OrderInfoProductType.NoPhotoProduct:                           //5不含照片的类型
                    spinHeight.Enabled = false;
                    spinWidth.Enabled = false;
                    spinPageNum.Enabled = true;
                    tsModifyPhotoHW.Visible = false;

                    ceProductWithoutPhoto.Checked = true;
                    break;
                case (int)OrderInfoProductType.NeedDesignPrint:               //需要设计的直出，开单时可输入尺寸，可输入P数
                    spinHeight.Enabled = true;
                    spinWidth.Enabled = true;
                    spinPageNum.Enabled = true;
                    tsModifyPhotoHW.Visible = false;

                    ceProductWithoutPhoto.Checked = false;
                    break;
                default:
                    spinHeight.Enabled = false;
                    spinWidth.Enabled = false;
                    spinPageNum.Enabled = false;
                    tsModifyPhotoHW.Visible = false;

                    ceProductWithoutPhoto.Checked = false;
                    break;
            }
        }

        #region "删除产品"按钮
        //"删除产品"按钮
        private void tsDeleteProduct_Click(object sender, EventArgs e)
        {
            try
            {
                if (ListProduct == null || gvProductList.SelectedRowsCount == 0)
                    return;
                int delIndex = gvProductList.GetSelectedRows()[0];
                StartOrderBLL.ProductInfo product = gvProductList.GetRow(delIndex) as StartOrderBLL.ProductInfo;

                string removePath = product.OrilOrderPath2;          //待删除产品的路径

                int productSerialID = product.ProductSerialID;
                DeleteProduct(productSerialID, removePath, false);
                gcProductList.RefreshDataSource();
                AfterDeleted();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
        #endregion

        #region Del键删除
        //Del键删除
        private void gvProductList_KeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                if (ListProduct == null || gvProductList.SelectedRowsCount == 0)
                    return;
                if (e.KeyData == Keys.Delete)
                {
                    int delIndex = gvProductList.GetSelectedRows()[0];
                    StartOrderBLL.ProductInfo product = gvProductList.GetRow(delIndex) as StartOrderBLL.ProductInfo;
                    int productSerialID = product.ProductSerialID;
                    string removePath = product.OrilOrderPath2;
                    DeleteProduct(productSerialID, removePath, false);
                    gcProductList.RefreshDataSource();
                    AfterDeleted();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
        #endregion

        #region 删除产品后的操作(重新设置当前产品)
        /// <summary>
        /// 删除产品后的操作(重新设置当前产品)
        /// </summary>
        private void AfterDeleted()
        {
            if (ListProduct == null || ListProduct.Count == 0)
            {
                //清空所有的信息
                ClearOrderBagCode();
                currentProduct = null;
            }
            else
            {
                StartOrderBLL.ProductInfo product = gvProductList.GetRow(0) as StartOrderBLL.ProductInfo;
                gvProductList.FocusedRowHandle = 0;
                currentProduct = ListProduct[0];
                isAddOldTech = true;                                                //表示是已添加的产品
                SetProductDetail(product.ProductSerialID);
                ComputeYJCompleteTime();
            }
        }
        //删除产品后重新计算预计完成时间
        private void ComputeYJCompleteTime()
        {
            double maxHour = 0;
            foreach (StartOrderBLL.ProductInfo p in ListProduct)
            {
                if (p.techs != null)
                {
                    double tempH = 0;
                    foreach (StartOrderBLL.STProductTech t in p.techs)
                    {
                        if (t.IsNeed == true)
                            tempH += t.NeedTime;
                    }
                    if (tempH > maxHour)
                        maxHour = tempH;
                }
            }
            OrderHours = maxHour;
            DateTime YJTime = DateTime.Now.AddHours(maxHour);
            dtFetchTime.Text = YJTime.ToString("yyyy-MM-dd HH:mm");
            dtYJCompleteTime.Text = YJTime.ToString("yyyy-MM-dd HH:mm");
        }
        #endregion

        #region 删除产品的操作
        /// <summary>
        /// 删除产品的操作
        /// </summary>
        /// <param name="productSerialID"></param>
        private void DeleteProduct(int productSerialID, string removePath, bool IsClearOrder)
        {
            if (IsClearOrder == false)          //删除产品
            {
                if (DialogResult.Yes != MessageBox.Show("确定要删除吗?", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Warning))
                    return;
            }
            foreach (StartOrderBLL.ProductInfo product in ListProduct)
            {
                if (product.ProductSerialID == productSerialID)
                {
                    ListProduct.Remove(product);
                    if (ListProduct.Count == 0)
                        currentShopPath = "";
                    //crc校验(去掉删除产品的crc码)      //new%%%新增产品；delete%%%删除产品；save%%%保存订单
                    if (IsNeedCheckPhotoRepeat == true)
                    {
                        if (clientSocket != null && clientSocket.Connected)
                        {
                            try
                            {
                                CrcCheck(product, "delete");
                            }
                            catch { }
                        }
                    }
                    //设置背景色
                    bool isFind = false;
                    foreach (TreeNode node in tvOrderPath.Nodes)
                    {
                        foreach (TreeNode subNode in node.Nodes)
                        {
                            if (subNode.Tag.ToString() == removePath)
                            {
                                subNode.BackColor = Color.Empty;
                                return;
                            }
                            foreach (TreeNode ssubNode in subNode.Nodes)
                            {
                                if (ssubNode.Tag.ToString() == removePath)
                                {
                                    ssubNode.BackColor = Color.Empty;
                                    isFind = true;
                                    break;
                                }
                            }
                            if (isFind == true)
                            {
                                bool isAllEmpty = true;            //当前客户下所有的产品是否都无背景色
                                foreach (TreeNode ssubNode in subNode.Nodes)
                                {
                                    if (ssubNode.BackColor == Color.Pink)
                                    {
                                        isAllEmpty = false;
                                        break;
                                    }
                                }
                                if (isAllEmpty == true)             //客户节点背景色根据产品背景色情况重新设置
                                    subNode.BackColor = Color.Empty;
                                break;
                            }
                        }
                        if (isFind == true)
                            break;
                    }

                    break;
                }
            }
        }
        #endregion

        #region 单击产品列表，显示该产品的明细
        //产品列表的单击操作,在产品信息部分显示其明细
        private void gvProductList_RowClick(object sender, DevExpress.XtraGrid.Views.Grid.RowClickEventArgs e)
        {
            if (e.RowHandle >= 0)
            {
                try
                {
                    if (e.Clicks == 1)
                    {
                        //保存上个产品明细
                        SaveCurrentProduct();
                        isAddOldTech = true;                                                //表示是已添加的产品
                        SetProductDetail(GetProductSerialId(e.RowHandle));
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
        }
        #endregion

        #region 根据当前行号获得产品序号
        /// <summary>
        /// 根据当前行号获得产品序号
        /// </summary>
        /// <param name="i"></param>
        /// <returns></returns>
        private int GetProductSerialId(int i)
        {
            try
            {
                StartOrderBLL.ProductInfo p = gvProductList.GetRow(i) as StartOrderBLL.ProductInfo;
                return p.ProductSerialID;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region 设置指定产品明细
        /// <summary>
        /// 设置指定产品明细
        /// </summary>
        /// <param name="productSerialID">产品系列ID</param>
        private void SetProductDetail(int productSerialID)
        {
            foreach (StartOrderBLL.ProductInfo product in ListProduct)
            {
                if (product.ProductSerialID == productSerialID)
                {
                    currentProduct = product;
                    //清除原有产品信息
                    ClearProductDetail();
                    SetEnableAndDisable(product.ProductTypeCode);                      //设置可用与不可用，可见与不可见
                    IsNewProduct = false;       //表示不是新添加的产品
                    txtProductName.Text = product.ProductName;
                    txtCtmName.Text = product.CtmName;

                    spinProductNum.Text = product.ProductNum.ToString();
                    spinPageNum.Text = product.PageNum.ToString();
                    float rh = product.Height;
                    float rw = product.Width;
                    float h = 0, w = 0;
                    string unit = cbUnit.Text;
                    switch (unit)
                    {
                        case "厘米(cm)":
                            h = rh * (float)2.54;
                            w = rw * (float)2.54;
                            break;
                        case "英寸(in)":
                            h = rh;
                            w = rw;
                            break;
                        case "米(m)":
                            h = rh * (float)2.54 / 100;
                            w = rw * (float)2.54 / 100;
                            break;
                        case "毫米(mm)":
                            h = rh * (float)2.54 * 10;
                            w = rw * (float)2.54 * 10;
                            break;
                    }
                    //设置高宽的可变范围
                    //SetMaxAndMin(h, w);
                    spinHeight.Text = string.Format("{0:0.####}", h);
                    spinWidth.Text = string.Format("{0:0.####}", w);
                    spinHeight.Tag = rh;
                    spinWidth.Tag = rw;
                    ceProductWithoutPhotoClick = false;//不是鼠标点击
                    ceProductOutReturnClick = false;
                    if (product.ProductType == 4)
                    {

                        ceProductWithoutPhoto.Checked = true;

                    }
                    else
                    {
                        ceProductWithoutPhoto.Checked = false;

                    }
                    if (product.ProductPayType == (int)OrderInfoType.OutReturnInfo)
                    {
                        checkEditOutReturn.Checked = true;
                    }
                    else
                    {
                        checkEditOutReturn.Checked = false;

                    }
                    foreach (StartOrderBLL.STPaperType paperType in ListPaperType)
                    {
                        if (product.PaperTypeID == paperType.PaperTypeID)
                        {
                            cbPaperType.Text = paperType.PaperTypeName;
                            break;
                        }
                        //if (product.PaperTypeName == paperType.PaperTypeName)
                        //{
                        //    cbPaperType.Text = paperType.PaperTypeName;
                        //    break;
                        //}
                    }
                    foreach (StartOrderBLL.STPaperFace paperFace in ListPaperFace)
                    {
                        if (product.PaperFaceID == paperFace.PaperFaceID)
                        {
                            cbPaperFace.Text = paperFace.PaperFaceName;
                            break;
                        }

                        //if (product.PaperFaceName == paperFace.PaperFaceName)
                        //{
                        //    cbPaperFace.Text = paperFace.PaperFaceName;
                        //    break;
                        //}
                    }
                    cbUnit.Text = product.Unit;
                    txtProductRemark.Text = product.ProductRemark;
                    lblPhotoNum.Text = product.PhotoNum.ToString();
                    lblProductArea.Text = product.PhotoAllArea.ToString();
                    cbPrinter.SelectedValue = product.PrinterId;        //打印机

                    //加载照片显示明细
                    AddPhotosInProduct(product);

                    //设置产品照片数量与总面积
                    SetPhotoNumAndArea(currentProduct.ProductTypeCode);                                  //参数需要改变
                    //SetPhotoNumAndArea("3");//按照照片的实际尺寸计算
                    gvProduct.ClearSelection();
                    //加载产品保存明细
                    //AddProductInfo(product);
                    //加载产品流程
                    singleProductTech = new List<StartOrderBLL.STProductTech>();
                    if (product.techs != null)
                    {
                        foreach (StartOrderBLL.STProductTech tech in product.techs)
                        {
                            singleProductTech.Add(tech);
                        }
                        AddProductFlow(singleProductTech);
                    }
                    break;
                }
            }
        }
        #endregion

        #region 开单
        //"开单"按钮
        private void tsStartOrder_Click(object sender, EventArgs e)
        {
            try
            {
                //保存当前产品
                SaveCurrentProduct();
                //SaveCurrentProductForOver();
                bool canStartOrder = CheckCanStartOrder();
                if (canStartOrder)                  //不满足开单条件
                    return;
                StartOrderType = 2;
                //新线程开单
                StartOrderCommon();
            }
            catch (Exception ex)
            {

                MessageBox.Show(ex.Message+ex.InnerException, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }


        //"开单并关闭"按钮
        private void tsStartOrderAndClose_Click(object sender, EventArgs e)
        {
            try
            {
                //保存当前产品
                SaveCurrentProduct();
                bool canStartOrder = CheckCanStartOrder();
                if (canStartOrder)                  //不满足开单条件
                    return;
                StartOrderType = 1;
                StartOrderCommon();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        /// <summary>
        /// 判断开单条件是否满足
        /// </summary>
        private bool CheckCanStartOrder()
        {
            txtOrderBagCode_Properties_Leave(new object(), new EventArgs());
            if (IsOrderBagExists)
                return true;
            string orderBagCode = txtOrderBagCode.Text.Trim();
            string orderName = txtOrderName.Text.Trim();
            if (cbPriority.Text.Length == 0)
            {
                MessageBox.Show("请选择加急级别!", "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return true;
            }
            string shopName = cbShopName.Text;
            if (shopName == "---请选择---")
            {
                MessageBox.Show("请选择商户!", "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return true;
            }
            if (ListProduct == null || ListProduct.Count == 0)
            {
                MessageBox.Show("无产品存在，不能开单!", "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return true;
            }
            foreach (StartOrderBLL.ProductInfo product in ListProduct)
            {
                if (product.ProductType == 1 || product.ProductType == 2)//3是正常产品完成，4是不需要照片产品完成
                {
                    MessageBox.Show("存在信息不足的产品，不能开单!", "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return true;
                }
                foreach (StartOrderBLL.STPhoto stPhoto in product.Photos)
                {
                    if(stPhoto.PixWidth==0||stPhoto.PixHeight==0)
                    {
                        MessageBox.Show("照片 "+stPhoto.PhotoFullPath+" 读取信息失败，请查看！", "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        return true;
                    }
                }
            }
            //CurrShopPaperType
            foreach (StartOrderBLL.ProductInfo product in ListProduct)
            {
                if (product.Photos == null || product.Photos.Count == 0)
                {
                    if (product.ProductType != 4)//3是不需要照片的产品
                    {
                        MessageBox.Show("存在无照片的产品，不能开单！", "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        return true;

                        //检查纸型存在不存在即改商户有没有该纸型的定价
                        MINERP.BLL.CustomerManage.StartOrderBLL.STPaperType stpaprttype = CurrShopPaperType.FirstOrDefault(p => p.PaperTypeName == product.PaperTypeName);

                        try
                        {
                            if (string.IsNullOrEmpty(stpaprttype.PaperTypeName))
                            {
                                MessageBox.Show(product.ProductName + "定义的纸型在该商户中未定义", "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                                return true;
                            }
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(product.ProductName + "定义的纸型在该商户中未定义", "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                            return true;
                        }
                    }

                }
                if (!product.IsCheckStyle)///未确定过设计产品的尺寸 
                {

                    if (product.techs.FirstOrDefault(p => p.IsDesign && p.IsNeed) != null)
                    {

                        if (!CheckSizeAndPage(product))
                        {
                            MessageBox.Show("请设置尺寸！", "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                            return true;
                        }
                    }
                }

            }
            int shopID = getShopId(shopName);
            if (orderBagCode == null || orderBagCode.Length == 0)
            {
                MessageBox.Show("订单包号不正确!", "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return true;
            }
            if (orderName == null || orderName.Length == 0)
            {
                MessageBox.Show("订单名称不能为空!", "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return true;
            }
            if (ListShop == null || ListShop.Count == 0)
            {
                MessageBox.Show("没有产品，不能开单!", "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return true;
            }
            if (shopID == 0)
            {
                MessageBox.Show("请指定商户!", "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return true;
            }
            return false;
        }

        #region 打开，关闭开单进度条
        /// <summary>
        /// 开单完成，关闭进度条
        /// </summary>
        private void CloseProgress()
        {
            frmPro.Close();
        }
        private void OpenProgress()
        {
            try
            {
                frmPro = new FrmProgress();
                frmPro.ShowDialog();
            }
            catch { }
        }
        #endregion

        //开单的公共操作
        delegate void delCloseProgress();
        int StartOrderType = 0;             //1开单并关闭 2连续开单
        FrmProgress frmPro = null;          //进度条页面
        private void StartOrderCommon()
        {
            try
            {
                string orderBagCode = txtOrderBagCode.Text.Trim();
                string orderName = txtOrderName.Text.Trim();
                string shopName = cbShopName.Text;
                int orderPriority = Convert.ToInt16(cbPriority.Text);
                List<StartOrderBLL.STShop> ListShop = SOBLL.ListShop;
                int shopID = 0;
                foreach (StartOrderBLL.STShop s in ListShop)
                {
                    if (s.ShopName == shopName)
                    {
                        shopID = s.ShopID;
                        break;
                    }
                }
                DateTime orderTime = Convert.ToDateTime(dtOrderTime.Text);
                DateTime preCompleteTime = Convert.ToDateTime(dtFetchTime.Text);//取件时间
                string orderRemark = txtShopRequire.Text;

                foreach (StartOrderBLL.ProductInfo p in ListProduct)            //替换掉中括号
                {
                    p.CtmName = p.CtmName.Replace('[', '(');
                    p.CtmName = p.CtmName.Replace(']', ')');
                    p.ProductName = p.ProductName.Replace('[', '(');
                    p.ProductName = p.ProductName.Replace(']', ')');
                    p.ProductName = p.ProductName.Replace('|', '-');
                }
                Thread th = new Thread(OpenProgress);
                th.IsBackground = true;
                try
                {
                    Cursor = Cursors.WaitCursor;
                    //子线程显示进度条
                    th.Start();
                    SOBLL.AddOrderBag(ListProduct, OrderID, orderBagCode, orderName, orderPriority, shopID, shopName, orderTime, preCompleteTime, orderRemark, UserID);
                    //移动照片(将照片移动到等待开单\已开单)
                    MoveDirectory(ListProduct);

                    //保存CRC码
                    if (IsNeedCheckPhotoRepeat == true)
                    {
                        try
                        {
                            CrcCheck(null, "save");
                        }
                        catch { }   //crc校验异常不作处理
                    }
                    this.Invoke(new delCloseProgress(CloseProgress));
                    th.Abort();
                    Cursor = Cursors.Default;
                    MessageBox.Show("开单成功!", "确认", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    //清空订单
                    ClearOrderBagCode();                //清空已开单的订单包信息
                    IsOpenedOrder = true;               //表示已真正开单
                    if (StartOrderType == 1)                      //开单并关闭
                    {
                        this.Close();
                    }
                    else if (StartOrderType == 2)                 //连续开单
                    {
                        //加载下一个占位订单
                        //订单包号
                        SOBLL.AddOrderBagTemp(out OrderID, out BagCode, UserID);
                        IsOpenedOrder = false;          //表示还未真正开单
                        if (btnCodeType.Text == "手动")
                        {
                            txtOrderBagCode.Text = BagCode;
                        }
                        else
                        {
                            SetOrderBagCode();
                        }
                        txtOrderName.Text = BagCode;
                        //设置时间
                        SetTime();
                        //刷新未开单的列表
                        //AddStartOrderPath();
                        RefreshStartOrderPath();
                    }

                    //计算预估结余

                }
                catch (Exception ex)
                {
                    this.Invoke(new delCloseProgress(CloseProgress));
                    th.Abort();
                    Cursor = Cursors.Default;
                    //MessageBox.Show(ConstString.StringCS.DataExceptionLink, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    MessageBox.Show(ex.Message+ex.InnerException.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }


            }
            catch (Exception ex)
            {
                if (ex is DirectoryNotFoundException)
                {
                    MessageBox.Show("目录创建失败:" + ex.InnerException.Message);
                }
            }
            finally
            {
                currentShopPath = "";                   //当前商户的路径设为空
            }
        }
        #endregion

        /// <summary>
        /// 移动所有开单的产品到已开单目录下
        /// </summary>
        /// <param name="products"></param>
        private void MoveDirectory(List<StartOrderBLL.ProductInfo> products)
        {
            try
            {
                foreach (StartOrderBLL.ProductInfo product in products)
                {
                    MoveSingleProduct(product);
                }
            }
            catch
            {
                throw new Exception("移动照片到\"已开单\"目录下失败，请手动移动");
            }
        }
        //API
        /// <summary>
        /// 移动文件，文件夹
        /// </summary>
        /// <param name="src"></param>
        /// <param name="dst"></param>
        /// <param name="flag">1如果文件存在，则替换；2如移动到不同的卷，则复制文件并删除原来的文件；3移动操作在系统重启后才真正执行</param>
        /// <returns></returns>
        [DllImport("kernel32", EntryPoint = "MoveFileEx", CharSet = CharSet.Unicode)]
        public static extern bool MoveFile(string src, string dst, long flag);

        private void MoveSingleProduct(StartOrderBLL.ProductInfo product)
        {
            try
            {
                string infoPath = "";             //产品路径
                string delPath = "";            //待删除的原始目录路径
                List<string> delPaths = new List<string>();
                List<string> unSucessPaths = new List<string>();
                foreach (StartOrderBLL.STPhoto photo in product.Photos)
                {
                    infoPath = photo.OldPicPath.Substring(0, photo.OldPicPath.LastIndexOf("\\"));
                    delPath = photo.PhotoFullPath.Substring(0, photo.PhotoFullPath.LastIndexOf("\\"));
                    
                    if (!Directory.Exists(infoPath))
                    {
                        Directory.CreateDirectory(infoPath);
                    }
                    if (!File.Exists(photo.OldPicPath))
                    {
                        File.SetAttributes(photo.PhotoFullPath, FileAttributes.Normal);
                        //File.Move(photo.PhotoFullPath, photo.OldPicPath);
                        if (MoveFile(photo.PhotoFullPath, photo.OldPicPath, 2))
                        {
                            if (!delPaths.Contains(delPath))
                            {
                                delPaths.Add(delPath);
                            }
                        }
                        else
                        {
                            if (!unSucessPaths.Contains(delPath))
                            {
                                unSucessPaths.Add(delPath);
                            }
                        }
                    }
                }
                foreach (string path in delPaths)
                {
                    SOBLL.DeleteDirectory(path);
                }
                if (unSucessPaths.Count > 0)
                {
                    throw new Exception(product.ProductName+"移动照片到\"已开单\"目录下失败，请手动移动,如果此错误出现频率很高请检查服务器或者局域网连接");
                }
            }
            catch
            {
            }
        }

        #region 清空已开单的订单包信息
        /// <summary>
        /// 清空已开单的订单包信息
        /// </summary>
        private void ClearOrderBagCode()
        {
            cbShopName.Text = "";
            txtProductName.Text = "";
            txtCtmName.Text = "";
            dtOrderTime.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm");
            dtYJCompleteTime.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm");
            dtFetchTime.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm");
            cbPaperType.Text = "";
            cbPaperFace.Text = "";
            spinHeight.Text = "0";
            spinWidth.Text = "0";
            txtShopRequire.Text = "";
            lblPhotoNum.Text = "0";
            lblProductArea.Text = "0";
            txtProductRemark.Text = "";
            //ListProduct.Clear();
            ListProduct.Clear();
            if (pProductFlow.Controls != null)
                pProductFlow.Controls.Clear();
            gcProductList.RefreshDataSource();
            gcProduct.DataSource = null;
            gcProduct.RefreshDataSource();
            currentProduct = null;                  //当前产品
            singleProductTech = null;               //当前产品流程
            IsSetFetchTime = false;                 //是否已手动设置取件时间
            OrderHours = 0;                         //当前订单的最大预计完成时间
            IsSetFetchTime = false;                 //取件时间没被开单员手动设置

        }
        #endregion

        //-----------------------------------------------
        //----------产品明细的操作-----------------------
        //-----------------------------------------------

        StartOrderBLL.ProductInfo currentProduct;               //当前的产品(专门用于操作当前产品)
        int currentSerialID = 0;                                //当前产品的系列ID
        List<string> ListAllPhotoPath = new List<string>();     //每次添加照片时，所有的照片路径集合
        bool IsNewProduct = true;                               //是否是新添加的产品
        //List<StartOrderBLL.STPhoto> currentPhotos = new List<StartOrderBLL.STPhoto>();  //当前产品照片的显示数据源
        List<PhotoListAndThumb> PhotoAndThumbList;              //产品的大对象集合
        //string OrilOrderPath = "";                              //产品内照片的原始目录                

        #region 加载产品默认流程
        /// <summary>
        /// 加载产品默认流程
        /// </summary>
        /// <param name="product"></param>
        private void AddProductFlow(List<StartOrderBLL.STProductTech> techs)
        {
            //产品默认流程
            pProductFlow.Controls.Clear();

            int i = techs.Count;
            int j = i;
            //techs = techs.OrderBy(p => p.WorkOrder).ToList();
            foreach (StartOrderBLL.STProductTech pt in techs)
            {
                if (!string.IsNullOrEmpty(pt.CommonChargeItems) && pt.IsNeed)
                {
                    string[] commItems = pt.CommonChargeItems.Split(',');
                    foreach (string str in commItems)
                    {
                        if (AllCostItem.FirstOrDefault(p => p.ItemName == str) == null)//没有的收费项目
                        {
                            MessageBox.Show("该商户的 " + str + " 收费项目未设置，请在后台添加该收费项目");
                        }
                    }
                }
                if (j != i)
                {
                    Label label = new Label();
                    label.Text = "->";
                    label.Dock = DockStyle.Left;
                    label.AutoSize = true;
                    pProductFlow.Controls.Add(label);

                }
                else
                    i--;
                //委外节点默认的委外商
                if (pt.Techtype == (int)TechType.OutProduct)         //9是指委外节点
                {
                    string osName = "";
                    List<MODEL.CustomerManage.StartOrder.ProductOutShop> pos = pt.Pos;
                    if (pt.OutShopId == 0)
                    {
                        osName = "(无委外商)";
                    }
                    else
                    {
                        foreach (MODEL.CustomerManage.StartOrder.ProductOutShop p in pos)
                        {
                            if (p.OutShopId == pt.OutShopId)
                            {
                                osName = "(" + p.OutShopName + ")";
                            }
                        }
                    }
                    LinkLabel llOutShop = new LinkLabel();
                    llOutShop.Text = osName;
                    llOutShop.Tag = pt;
                    llOutShop.Dock = DockStyle.Left;
                    llOutShop.AutoSize = true;
                    llOutShop.Click += new EventHandler(llOutShop_Click);
                    pProductFlow.Controls.Add(llOutShop);
                }
                //商户节点的默认操作员工
                string userName = "(无)";
                if (pt.UserId != 0)
                {
                    foreach (MODEL.CustomerManage.StartOrder.User u in AllUser)
                    {
                        if (u.UserId == pt.UserId)
                        {
                            userName = "(" + u.UserName + ")";
                            break;
                        }
                    }
                }
                LinkLabel lluser = new LinkLabel();
                if (pt.Techtype == (int)TechType.TiaoSe)                 //调色结点加上快捷键
                {
                    lluser.Name = "llTS";           //加快捷键使用
                }
                lluser.Text = userName;
                lluser.Click += new EventHandler(lluser_Click);
                lluser.Tag = pt;
                lluser.Dock = DockStyle.Left;
                lluser.AutoSize = true;
                lluser.TextAlign = ContentAlignment.BottomCenter;
                pProductFlow.Controls.Add(lluser);
                //checkbox
                CheckBox cb = new CheckBox();
                cb.Text = pt.TechName;
                cb.Dock = DockStyle.Left;
                cb.AutoSize = true;
                if (pt.IsNeed)
                {
                    cb.Checked = true;
                }
                else
                {
                    cb.Checked = false;
                }
                if (isAddOldTech == true && pt.IsNeed == false)     //如果是已有产品，且当前流程不需要时
                {
                    cb.Checked = false;
                }
                //if (isAddOldTech == false)
                //    pt.IsNeed = true;
                cb.CheckedChanged += new EventHandler(cb_CheckedChanged);
                if (pt.IsNessesary == true)
                    cb.Enabled = false;


                pProductFlow.Controls.Add(cb);
                //if (pt.IsDesign)
                //{
                //    if (pt.CommonChargeItems.Contains("设计"))
                //    {

                //        if (!cb.Checked)
                //        {
                //            cb.Checked = true;
                //        }
                //    }
 
                //}
            }
            if (pProductFlow.HorizontalScroll.Visible == true) //需要水平滚动条时
            {
                if (IsAddedScroll == false)
                {
                    spcProductDetail.SplitterDistance += 15;
                    pProductFlow.Height += 15;
                    labelControl15.Location = new Point(labelControl15.Location.X, labelControl15.Location.Y + 15);
                    txtProductRemark.Location = new Point(txtProductRemark.Location.X, txtProductRemark.Location.Y + 15);
                    IsAddedScroll = true;
                }
            }
            else
            {
                if (IsAddedScroll == true)
                {
                    spcProductDetail.SplitterDistance -= 15;
                    pProductFlow.Height -= 15;
                    labelControl15.Location = new Point(labelControl15.Location.X, labelControl15.Location.Y - 15);
                    txtProductRemark.Location = new Point(txtProductRemark.Location.X, txtProductRemark.Location.Y - 15);
                    IsAddedScroll = false;
                }
            }
        }

        //修改委外节点默认委外商
        void llOutShop_Click(object sender, EventArgs e)
        {
            try
            {
                LinkLabel llOutShop = (LinkLabel)sender;
                StartOrderBLL.STProductTech pt = (StartOrderBLL.STProductTech)llOutShop.Tag;
                FrmSetOutShop frm = new FrmSetOutShop();
                frm.OldOutShopId = pt.OutShopId;
                frm.Pos = pt.Pos;
                frm.frm = this;
                if (DialogResult.OK == frm.ShowDialog())
                {
                    llOutShop.Text = "(" + SelectedOutShopName + ")";
                    pt.OutShopId = SelectedOutShopId;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        //修改节点默认操作员工
        void lluser_Click(object sender, EventArgs e)
        {
            try
            {
                FrmSetUser frm = new FrmSetUser();
                LinkLabel lluser = (LinkLabel)sender;
                StartOrderBLL.STProductTech pt = (StartOrderBLL.STProductTech)lluser.Tag;
                List<MODEL.CustomerManage.StartOrder.User> filterUser = GetTechUser(pt.TechID);
                if (filterUser.Count == 1)
                    return;
                frm.UserId = pt.UserId;
                frm.frm = this;
                frm.FilterUser = filterUser;
                if (frm.ShowDialog() == DialogResult.OK)
                {
                    pt.UserId = SelectedUserId;
                    lluser.Text = "(" + SelectedUserName + ")";
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
        /// <summary>
        /// 获取指定节点可用的员工列表
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        List<MODEL.CustomerManage.StartOrder.User> GetTechUser(int userId)
        {
            try
            {
                List<MODEL.CustomerManage.StartOrder.User> filterUser = new List<MINERP.MODEL.CustomerManage.StartOrder.User>();
                MODEL.CustomerManage.StartOrder.User nullUser = new MINERP.MODEL.CustomerManage.StartOrder.User();
                filterUser.AddRange(AllUser.FindAll(p => p.TechId == userId && p.IsOnline == true));
                filterUser = filterUser.OrderBy(p => p.UserName).ToList();
                nullUser.UserId = 0;
                nullUser.UserName = "无";
                filterUser.Insert(0, nullUser);
                return filterUser;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        //流程是否取消
        void cb_CheckedChanged(object sender, EventArgs e)
        {
            try
            {
                CheckBox cb = sender as CheckBox;
                if (cb != null)
                {
                    foreach (StartOrderBLL.STProductTech tech in singleProductTech)
                    {
                        if (tech.TechName == cb.Text)
                        {
                            if (cb.Checked == true)
                            {
                                if (AllCostItem != null && !string.IsNullOrEmpty(tech.CommonChargeItems))
                                {
                                    if (AllCostItem.FirstOrDefault(p => p.ItemName == tech.CommonChargeItems) != null)
                                    {
                                        tech.IsNeed = true;
                                        //计算产品用时
                                        currentProduct.ProductHours += tech.NeedTime;
                                        CompareMaxHour();
                                        //新增设计节点时输入尺寸
                                        if (tech.IsDesign)
                                        {
                                            CheckSizeAndPage(currentProduct);
                                            //currentProduct.IsNeedDesign = true;//需要设计
                                        }
                                        //添加节点的收费项目   
                                        if (currentProduct.StringCostItems == null)
                                        {
 currentProduct.StringCostItems="";
                                        }
                                        if (currentProduct.StringCostItems != null && currentProduct.StringCostItems.IndexOf(tech.CommonChargeItems) < 0)
                                        {
                                            currentProduct.StringCostItems = currentProduct.StringCostItems + "," + tech.CommonChargeItems + ",";
                                            currentProduct.StringCostItems = currentProduct.StringCostItems.Trim(',');

                                        }
                                    }

                                    else
                                    {
                                        cb.Checked = false;
                                        MessageBox.Show("该商户的 " + tech.CommonChargeItems + " 收费项目未添加，请在后台添加该收费项目", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

                                    }
                                }
                                else
                                {
                                    tech.IsNeed = true;
                                    //计算产品用时
                                    currentProduct.ProductHours += tech.NeedTime;
                                    CompareMaxHour();

                                }
                            }
                            else
                            {
                                tech.IsNeed = false;
                                //计算产品用时
                                currentProduct.ProductHours -= tech.NeedTime;
                                CompareMaxHour();
                                if (tech.IsDesign)//设计节点
                                {
                                    currentProduct.IsNeedDesign = false;

                                }
                                if (currentProduct.StringCostItems!=null&&currentProduct.StringCostItems.Contains(tech.TechName))
                                {
                                    //删除节点的收费项目
                                    string aaa = tech.CommonChargeItems + ",";
                                    string bbb = tech.CommonChargeItems;
                                    if (!string.IsNullOrEmpty(currentProduct.StringCostItems))
                                    {
                                        int aIndex = currentProduct.StringCostItems.IndexOf(aaa);
                                        int bIndex = currentProduct.StringCostItems.IndexOf(bbb);
                                        if (aIndex >= 0)
                                        {
                                            currentProduct.StringCostItems = currentProduct.StringCostItems.Remove(aIndex, aaa.Length);
                                        }
                                        else if (bIndex > 0)
                                        {
                                            currentProduct.StringCostItems = currentProduct.StringCostItems.Remove(bIndex - 1, bbb.Length + 1);
                                        }
                                        else if (bIndex == 0)
                                        {
                                            currentProduct.StringCostItems = currentProduct.StringCostItems.Remove(bIndex, bbb.Length);

                                        }
                                    }
                                }
                            }
                            break;
                        }
                    }
                    gcProductList.RefreshDataSource();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
        #endregion


        #region 验证设计时尺寸和P数
        public bool CheckSizeAndPage(StartOrderBLL.ProductInfo currProduct)
        {
            FrmCheckSizeAndPage frmCheckSizeAndPage = new FrmCheckSizeAndPage(currProduct);
            frmCheckSizeAndPage.PageNum = currProduct.ProductModel.PageNum;
            frmCheckSizeAndPage.Width = currProduct.ProductModel.Width;
            frmCheckSizeAndPage.Height = currProduct.ProductModel.Height;
            frmCheckSizeAndPage.SizeUnit = "英寸(in)";
            currProduct.IsNeedDesign = true;
            if (DialogResult.OK == frmCheckSizeAndPage.ShowDialog())
            {

                spinPageNum.Text = frmCheckSizeAndPage.PageNum.ToString();

                spinHeight.Tag = frmCheckSizeAndPage.Height;
                spinWidth.Tag = frmCheckSizeAndPage.Width;
                cbUnit.Text = frmCheckSizeAndPage.SizeUnit;
                spinPageNum.Value = frmCheckSizeAndPage.PageNum;//需要设计的产品安装输入计算
                currProduct.IsCheckStyle = true;

                return true;
            }
            else
            {
                currProduct.IsCheckStyle = false;
                return false;
            }

        }
        #endregion

        #region 加载指定产品内所有的产品信息(用于显示)
        /// <summary>
        /// 加载一个产品内所有的照片显示信息
        /// </summary>
        /// <param name="product">产品</param>
        private void AddPhotosInProduct(StartOrderBLL.ProductInfo product)
        {
            //currentPhotos.Clear();                                  //清空上一个产品的照片显示信息
            List<StartOrderBLL.STPhoto> photos = product.Photos;
            browser = new RasterThumbnailBrowser();
            browser.Dock = DockStyle.Fill;
            browser.SelectionMode = RasterImageListSelectionMode.Multi;
            browser.KeyDown += new KeyEventHandler(browser_KeyDown);
            gcProduct.DataSource = photos;
            if (photos != null)
            {
                PhotoAndThumbList = new List<PhotoListAndThumb>();      //大对象
                foreach (StartOrderBLL.STPhoto photo in photos)                       //加入大对象
                {
                    PhotoListAndThumb pat = new PhotoListAndThumb();
                    pat.Item = photo;
                    pat.ThumbIsAdded = false;
                    PhotoAndThumbList.Add(pat);
                }
            }
            SetPhotoProperty(false);                                         //设置照片属性,不需要制定默认尺寸
        }
        #endregion

        #region 加载指定产品原有的信息(用于保存)
        /// <summary>
        /// 加载指定产品的保存信息 
        /// </summary>
        /// <param name="product"></param>
        private void AddProductInfo(StartOrderBLL.ProductInfo product)
        {
            currentProduct = new StartOrderBLL.ProductInfo();
            currentProduct.ProductID = product.ProductID;
            currentProduct.ProductName = product.ProductName;
            currentProduct.ProductSerialID = product.ProductSerialID;
            
        }
        #endregion

        #region 显示的单位发生变化的按钮
        //显示的单位发生变化的按钮
        private void cbUnit_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                string unitStr = cbUnit.Text;
                int index = unitStr.IndexOf("(");
                string unit = unitStr.Substring(0, index);
                DisplayByUnit(unitStr);
                ChangeDataSourceByUnit();   //按不同的单位重新显示
                if (currentProduct != null)
                {
                    //SetPhotoNumAndArea(currentProduct.productTypeRemark);                        //设置照片数量与面积
                    SetPhotoNumAndArea((int)OrderInfoProductType.NoNeedDesignPrint);                        //实际照片的尺寸

                }
                SetProductHW();                                                             //按单位设置产品的高宽
                //保存单位
                Properties.Settings.Default.PreviousUnit = cbUnit.Text;
                Properties.Settings.Default.Save();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
        #endregion

        #region 照片列表头部,单位变化，显示随着变化
        /// <summary>
        /// 照片列表头部,单位变化，显示随着变化
        /// </summary>
        private void DisplayByUnit(string unit)
        {
            string disUnit = "";
            string disUnitArea = "";
            switch (unit)
            {
                case "厘米(cm)":
                    disUnit = "高×宽(厘米)";
                    disUnitArea = "面积(平方厘米)"; break;
                case "英寸(in)":
                    disUnit = "高×宽(英寸)";
                    disUnitArea = "面积(平方英寸)"; break;
                case "米(m)":
                    disUnit = "高×宽(米)";
                    disUnitArea = "面积(平方米)"; break;
                case "毫米(mm)":
                    disUnit = "高×宽(毫米)";
                    disUnitArea = "面积(平方毫米)"; break;
            }
            gvProduct.Columns["PhotoHW"].Caption = disUnit;
            gvProduct.Columns["PhotoArea"].Caption = disUnitArea;
        }
        #endregion

        #region "打开目录"按钮
        //"打开目录"按钮 
        private void tsOpenDirectory_Click(object sender, EventArgs e)
        {
            try
            {
                if (ListProduct.Count <= 0)
                {
                    MessageBox.Show("还未选择产品!", "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                if (DisplayMode == true)
                {
                    tsExchange_Click(sender, e);
                }
                string directoryPath = Properties.Settings.Default.StartOrderDirectory;
                if (Directory.Exists(directoryPath))
                {
                    folderBrowserDialog1.SelectedPath = directoryPath;
                }
                if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
                {
                    string photoPath = folderBrowserDialog1.SelectedPath;
                    //执行加载照片操作
                    AddPhotoByDirectory(photoPath);

                    //保存本次使用的路径 
                    Properties.Settings.Default.StartOrderDirectory = photoPath;
                    Properties.Settings.Default.Save();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
        #endregion

        #region "打开文件"按钮
        //"打开文件"按钮
        private void tsOpenFile_Click(object sender, EventArgs e)
        {
            try
            {
                if (ListProduct.Count <= 0)
                {
                    MessageBox.Show("还未选择产品!", "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                if (DisplayMode == true)
                {
                    tsExchange_Click(sender, e);
                }
                string directoryPath = Properties.Settings.Default.StartOrderFile;
                if (Directory.Exists(directoryPath))
                {
                    openFileDialog1.InitialDirectory = directoryPath;
                }
                if (openFileDialog1.ShowDialog() == DialogResult.OK)
                {
                    //执行加载照片操作
                    string[] filePaths = openFileDialog1.FileNames;
                    AddPhotoByFiles(filePaths);

                    //保存本次使用的照片所在的目录路径
                    FileInfo finfo = new FileInfo(filePaths[0]);
                    string photpPath = finfo.Directory.FullName;
                    Properties.Settings.Default.StartOrderFile = photpPath;
                    Properties.Settings.Default.Save();
                    SetPhotoNumAndArea(currentProduct.ProductTypeCode);                      //参数需要改变
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
        #endregion

        #region 获取指定目录下所有的照片路径集合
        /// <summary>
        /// 获取指定目录下所有的照片路径集合
        /// </summary>
        /// <param name="directory">目录路径</param>
        private void GetAllPhotoPath(string directory)
        {
            string[] subDirectorys = Directory.GetDirectories(directory);
            foreach (string subDirectory in subDirectorys)
            {
                GetAllPhotoPath(subDirectory);
            }
            string pattern = "*.jpg|*.tif|*.jpeg|*.tiff";
            string[] subFiles = GetFilesByPatterns(directory, pattern);
            foreach (string subFile in subFiles)
            {
                ListAllPhotoPath.Add(subFile);
            }
        }
        #endregion

        #region 根据指定的筛选格式获取指定的照片
        /// <summary>
        /// 根据指定的筛选格式获取指定的照片
        /// </summary>
        /// <param name="directory"></param>
        /// <param name="pattern"></param>
        /// <returns></returns>
        private string[] GetFilesByPatterns(string directory, string pattern)
        {
            string[] allFiles;
            List<string> listFiles = new List<string>();
            string[] ps = pattern.Split('|');
            foreach (string p in ps)
            {
                string[] pfiles = Directory.GetFiles(directory, p);
                listFiles = listFiles.Concat(pfiles).ToList();
                //foreach (string f in pfiles)
                //    listFiles.Add(f);
            }
            //allFiles = new string[listFiles.Count];
            //for (int i = 0; i < listFiles.Count; i++)
            //{
            //    allFiles[i] = listFiles[i];
            //}
            allFiles = listFiles.ToArray();
            return allFiles;
        }
        #endregion

        #region 加载一个目录下所有的照片
        /// <summary>
        /// 加载一个目录下所有的照片
        /// </summary>
        /// <param name="directory"></param>
        private void AddPhotoByDirectory(string directory)
        {
            //OrilOrderPath = directory;
            ListAllPhotoPath.Clear();   //先将保存照片目录的集合清空
            GetAllPhotoPath(directory);
            CheckIsNewProduct();        //判断是否是新加的产品，即是否还未添加照片信息



            RasterCodecs.Startup();
            RasterCodecs codecs = new RasterCodecs();
            foreach (string file in ListAllPhotoPath)
            {
                AddSinglePhotoNoDesign(file, codecs);
            }
            codecs.Dispose();
            RasterCodecs.Shutdown();
            gcProduct.RefreshDataSource();
            SetPhotoNumAndArea(currentProduct.ProductTypeCode);                        //设置照片数量与面积
        }
        #endregion

        #region 加载指定路径数组的一系列照片
        /// <summary>
        /// 加载指定路径数组的一系列照片
        /// </summary>
        /// <param name="files"></param>
        private void AddPhotoByFiles(string[] files)
        {
            if (files.Length > 0)
            {
                FileInfo fileInfo = new FileInfo(files[0]);
                //OrilOrderPath = fileInfo.Directory.FullName;
            }

            //---------------------------------------------------
            CheckIsNewProduct();        //判断是否是新加的产品，即是否还未添加照片信息

            RasterCodecs.Startup();
            RasterCodecs codecs = new RasterCodecs();
            foreach (string file in files)
            {
                AddSinglePhotoNoDesign(file, codecs);
            }
            codecs.Dispose();
            RasterCodecs.Shutdown();
            gcProduct.RefreshDataSource();
            //SetPhotoNumAndArea(currentProduct.productTypeRemark);                        //设置照片数量与面积
            SetPhotoNumAndArea((int)OrderInfoProductType.NoNeedDesignPrint);//计算照片的本身的面积
        }
        /// <summary>
        /// crc校验
        /// </summary>
        /// <param name="product"></param>
        /// <param name="type"></param>
        private int CrcCheck(StartOrderBLL.ProductInfo product, string type)
        {
            if (clientSocket != null && clientSocket.Connected == false)
            {
                return 1;       //表示连接已关闭
            }
            else if (clientSocket != null && clientSocket.Connected)
            {
                //new%%%新增产品；delete%%%删除产品；save%%%保存订单
                byte[] bytes = new byte[1024];
                string path = type + "%%%";
                if (product != null)                //产品参数为空表示是保存订单
                {
                    MINERP.BLL.CustomerManage.StartOrderBLL.STPhoto photo = product.Photos.OrderBy(p => p.PhotoLength).First();    //最小的照片
                    path += photo.PhotoFullPath;
                }
                bytes = System.Text.Encoding.Unicode.GetBytes(path);
                clientSocket.Send(bytes);
                if (type == "new")                      //新增产品有返回值
                {
                    byte[] receive = new byte[8];
                    int len = clientSocket.Receive(receive);
                    string r = System.Text.Encoding.Unicode.GetString(receive, 0, len);     //0表示存在 1表示不存在 2表示crc码保存进数据库成功 3表示crc码保存进数据库失败
                    if (r == "0")           //如果CRC码已存在，需提示
                    {
                        MessageBox.Show("“" + product.ProductName + "”可能已经开过单，请检查！", "确定", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                }
                return 2;               //表示操作正常
            }
            return 2;                   //表示操作正常
        }
        #endregion

        #region 产品照片的拖曳操作
        private void gcProduct_DragEnter(object sender, DragEventArgs e)
        {
            try
            {
                if (e.Data.GetDataPresent(DataFormats.FileDrop) || e.Data.GetDataPresent("list")) //后者是拖曳产品
                {
                    if (ListProduct.Count <= 0)
                    {
                        return;
                    }
                    e.Effect = DragDropEffects.All;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        private void gcProduct_DragDrop(object sender, DragEventArgs e)
        {
            try
            {
                if (e.Data.GetDataPresent(DataFormats.FileDrop))
                {
                    object data = e.Data.GetData(DataFormats.FileDrop);
                    string[] paths = (string[])data;
                    if (paths.Length == 1)  //可能是目录或照片
                    {
                        if (Directory.Exists(paths[0]))
                        {
                            AddPhotoByDirectory(paths[0]);
                        }
                        else
                        {
                            AddPhotoByFiles(paths);
                        }
                    }
                    else                    //只可能是照片数组
                    {
                        AddPhotoByFiles(paths);
                    }
                }
                else if (e.Data.GetDataPresent("list"))
                {
                    List<string> productPaths = e.Data.GetData("list") as List<string>;
                    if (productPaths.Count > 1)
                    {
                        MessageBox.Show("不能一次拖入多个产品明细!", "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        return;
                    }
                    else if (currentProduct.ProductType != 2)                                  //1真实产品 2模板 3二者都有
                    {
                        MessageBox.Show("无法和指定的产品模板匹配!", "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        return;
                    }
                    else                                                                        //与产品模板进行匹配
                    {
                        currentNode.BackColor = Color.Pink;
                        AddProductOnModel(productPaths[0]);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
        #endregion

        #region 判断是否是新加的产品，即是否还未添加照片信息
        /// <summary>
        /// 判断是否是新加的产品，即是否还未添加照片信息
        /// </summary>
        private void CheckIsNewProduct()
        {
            if (IsNewProduct == true)       //在下部产品明细中，新产品还未设置照片
            {
                //ListProductDataSource = new List<StartOrderBLL.STPhoto>();
                PhotoAndThumbList = new List<PhotoListAndThumb>();  //大对象
                browser = new RasterThumbnailBrowser();             //缩略图对象
                browser.Dock = DockStyle.Fill;
                browser.SelectionMode = RasterImageListSelectionMode.Multi;
                browser.KeyDown += new KeyEventHandler(browser_KeyDown);
                IsNewProduct = false;           //表示已添加部分照片信息
            }
        }


        #endregion

        #region 加载单个照片(分为需要设计、不需要设计)
        /// <summary>
        /// 加载单个文件(需要设计)
        /// </summary>
        /// <param name="fileFullPath"></param>
        private void AddSingleFile(string fileFullPath)
        {
            foreach (StartOrderBLL.STPhoto p in currentProduct.Photos)        //判断照片是否已添加
            {
                if (fileFullPath == p.PhotoFullPath)
                    return;
            }
            StartOrderBLL.STPhoto photo = AddPhotoCommon(fileFullPath);
            //currentPhotos.Add(photo);
            List<StartOrderBLL.STPhoto> photos = gcProduct.DataSource as List<StartOrderBLL.STPhoto>;
            photos.Add(photo);

            //保存进大对象
            PhotoListAndThumb pat = new PhotoListAndThumb();
            pat.Item = photo;
            pat.ThumbIsAdded = false;   //表示还未添加缩略图
            PhotoAndThumbList.Add(pat);
        }

        /// <summary>
        /// 加载单个文件(不需要设计)
        /// </summary>
        /// <param name="fileFullPath"></param>
        /// <param name="codecs"></param>
        private void AddSinglePhotoNoDesign(string fileFullPath, RasterCodecs codecs)
        {
            foreach (StartOrderBLL.STPhoto p in currentProduct.Photos)    //判断照片是否已添加
            {
                if (p.PhotoFullPath == fileFullPath)
                    return;
            }
            StartOrderBLL.STPhoto photo = AddPhotoCommon(fileFullPath);
            CodecsImageInfo imgInfo = codecs.GetInformation(fileFullPath, true);
            int resolution = imgInfo.XResolution;
            int xPixel = imgInfo.Width;
            int yPixel = imgInfo.Height;

            float standardWidth = (float)xPixel / resolution;
            float standardHeight = (float)yPixel / resolution;
            
            //照片分辨率
            photo.PhotoDPI = resolution;
            //照片标准高宽，用于计算
            photo.PhotoStandardHCompute = standardHeight;
            photo.PhotoStandardWCompute = standardWidth;
            //标准高宽，用于显示
            string standardHW = string.Format("{0:0.##}", standardHeight) + "×" + string.Format("{0:0.##}", standardWidth);
            photo.PhotoHWStandard = standardHW;
            //标准面积
            string standardArea = string.Format("{0:0.##}", standardWidth * standardHeight);
            photo.PhotoAreaStandard = standardArea;
            //照片像素高、宽
            photo.PixHeight = yPixel;
            photo.PixWidth = xPixel;
            if (yPixel == 0 || xPixel == 0)
            {
                MessageBox.Show("照片 " + fileFullPath + " 未能读取成功，请检查", "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);

            }
            //高宽、面积需要按单位的不同作不同的显示
            photo = DisplayHWByUnit(photo);

            //照片的原路径
            
            //RasterViewPerspective perspcetive = imgInfo.ViewPerspective;


            //ListProductDataSource.Add(photo);
            //显示照片对象
            //currentPhotos.Add(photo);
            List<StartOrderBLL.STPhoto> photos = gcProduct.DataSource as List<StartOrderBLL.STPhoto>;
            photos.Add(photo);


            //保存进大对象
            PhotoListAndThumb pat = new PhotoListAndThumb();
            pat.Item = photo;
            pat.ThumbIsAdded = false;   //表示还未添加缩略图
            PhotoAndThumbList.Add(pat);

            /*
            //检查照片是否已开过单
            if (IsNeedCheckPhotoRepeat == true)     //需要检查照片是否开过单才检查
            {
                //DateTime start = DateTime.Now;
                byte[] buffers = File.ReadAllBytes(fileFullPath);
                crc.Reset();
                crc.Crc(buffers);
                //DateTime end = DateTime.Now;
                //MessageBox.Show((end - start).ToString());
                string crcMark = crc.Value.ToString();
                if (FrmManage.ListCRC.Contains(crcMark))
                {
                    MessageBox.Show("\"" + fileFullPath + "\"已开过单", "确定", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
                //int r = FrmManage.ListCRC.IndexOf(crcMark);
                //if (r < 0)
                //{
                //    MessageBox.Show("\"" + fileFullPath + "\"已开过单", "确定", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                //}
                photo.CrcMark = crcMark;
                FrmManage.ListCRC.Add(crcMark);
            }
             * */
        }
        #endregion

        #region 加载照片的中间操作
        /// <summary>
        /// 加载照片的中间操作
        /// </summary>
        /// <param name="fileFullPath"></param>
        /// <returns></returns>
        private StartOrderBLL.STPhoto AddPhotoCommon(string fileFullPath)
        {
            StartOrderBLL.STPhoto photo = new StartOrderBLL.STPhoto();
            FileInfo fileInfo = new FileInfo(fileFullPath);
            //照片全路径
            photo.PhotoFullPath = fileInfo.FullName;
            //照片名称
            photo.PhotoName = fileInfo.Name;
            //照片数量
            photo.PhotoNum = 1;
            //照片大小
            string sizeStr = "";
            long fileSize = fileInfo.Length;
            photo.PhotoLength = fileSize;           //在CRC校验中，取同一个产品中长度最长的照片比较
            if (fileSize < 1024)
            {
                sizeStr = fileSize.ToString() + "B";
            }
            else if (fileSize < 1024 * 1024)
            {
                sizeStr = string.Format("{0:0.##}", (double)fileSize / 1024) + "K";
            }
            else if (fileSize < 1024 * 1024 * 1024)
            {
                sizeStr = string.Format("{0:0.##}", (double)fileSize / 1024 / 1024) + "M";
            }
            else
            {
                sizeStr = string.Format("{0:0.##}", (double)fileSize / 1024 / 1024 / 1024) + "G";
            }
            photo.PhotoSize = sizeStr;
            //照片备注(默认为照片名)

            //int index = fileInfo.Name.LastIndexOf(".");
            //string[] patharry = fileInfo.FullName.Split('\\');
            //int intPoint = patharry.Length - 2;
            //string strTemp = patharry[patharry.Length - 1];
            int index1 = fileInfo.FullName.IndexOf("等待开单");
            string strTempPath = fileInfo.FullName.Substring(index1);//从等等开单的临时的文路径

            int index = strTempPath.LastIndexOf(".");
            string[] patharry = strTempPath.Split('\\');
            string strTemp = patharry[patharry.Length - 1];


            for (int i = patharry.Length - 2; i > 2; i--)
            {
                strTemp = patharry[i] + "\\" + strTemp;
            }

            photo.PhotoRemark = strTemp;
            //photo.PhotoName = strTemp;


            //if (intPoint >= 0)
            //{
            //    photo.PhotoRemark = patharry[intPoint] + "\\" + fileInfo.Name.Substring(0, index);
            //    photo.PhotoName = patharry[intPoint] + "\\" + photo.PhotoName;
            //    //福州不要，北京要
            //}
            //else
            //{
            //    photo.PhotoRemark = fileInfo.Name.Substring(0, index);
            //}

            return photo;
        }
        #endregion

        #region 照片的高宽、面积按不同的单位作不同的显示
        /// <summary>
        /// 根据不同单位，重新设置产品明细数据源的显示
        /// </summary>
        private void ChangeDataSourceByUnit()
        {
            if (currentProduct != null && currentProduct.Photos.Count > 0)
            {
                for (int i = 0; i < currentProduct.Photos.Count; i++)
                {
                    currentProduct.Photos[i] = DisplayHWByUnit(currentProduct.Photos[i]);
                }
                gcProduct.RefreshDataSource();
            }
        }
        /// <summary>
        /// 照片的高宽、面积按不同的单位作不同的显示
        /// </summary>
        /// <param name="photo"></param>
        private StartOrderBLL.STPhoto DisplayHWByUnit(StartOrderBLL.STPhoto photo)
        {
            float height = photo.PhotoStandardHCompute;
            float width = photo.PhotoStandardWCompute;
            string hw = "";
            string area = "";
            string unit = cbUnit.Text.Trim();
            switch (unit)
            {
                case "厘米(cm)":
                    hw = string.Format("{0:0.##}", height * 2.54) + "×" + string.Format("{0:0.##}", width * 2.54);
                    area = string.Format("{0:0.##}", height * width * 2.54 * 2.54);
                    break;
                case "英寸(in)":
                    hw = string.Format("{0:0.##}", height) + "×" + string.Format("{0:0.##}", width);
                    area = string.Format("{0:0.##}", height * width);
                    break;
                case "米(m)":
                    hw = string.Format("{0:0.####}", height * 2.54 * 0.01) + "×" + string.Format("{0:0.##}", width * 2.54 * 0.01);
                    area = string.Format("{0:0.####}", height * width * 2.54 * 2.54 * 0.01 * 0.01);
                    break;
                case "毫米(mm)":
                    hw = string.Format("{0:0.##}", height * 2.54 * 10) + "×" + string.Format("{0:0.##}", width * 2.54 * 10);
                    area = string.Format("{0:0.##}", height * width * 2.54 * 2.54 * 10 * 10);
                    break;
            }
            photo.Unit = unit;
            photo.PhotoHW = hw;
            photo.PhotoArea = area;
            return photo;
        }
        #endregion

        #region 设置照片数量与面积
        /// <summary>
        /// 设置照片数量与面积
        /// </summary>
        /// <param name="photo">产品</param>
        private void SetPhotoNumAndArea(int ProductTypeCode)                       //产品是扩印还是非扩印
        {
            if (currentProduct.Photos.Count != 0)
            {
                int photoNum = 0;
                float h = (float)Convert.ToDouble(spinHeight.Tag);
                float w = (float)Convert.ToDouble(spinWidth.Tag);
                int productNum = Convert.ToInt16(spinProductNum.Text.Trim());           //产品份数                      
                float areaStandard = 0;                                                 //标准面积
                float area = 0;
                if (gcProduct.DataSource != null)                                       //表示当前无产品
                {
                    if (ProductTypeCode == (int)OrderInfoProductType.NeedDesignPrint || ProductTypeCode == (int)OrderInfoProductType.NeedDesignProduct || ProductTypeCode == (int)OrderInfoProductType.NeedDesignKuoYin)             //实质是ProductTypeCode。按产品的尺寸计算总面积
                    {
                        int pageNum = Convert.ToInt16(spinPageNum.Text.Trim());         //Page数
                        areaStandard = h * w * pageNum * productNum;

                    }
                    else                                                                //按照片本身的面积计算总面积
                    {
                        //冲印产品的设置
                        foreach (StartOrderBLL.STPhoto photo in currentProduct.Photos)
                        {
                            areaStandard += (float)Convert.ToDouble(photo.PhotoAreaStandard);
                        }
                        areaStandard *= productNum;
                    }
                    photoNum = currentProduct.Photos.Count;
                }

                switch (cbUnit.Text.Trim())
                {
                    case "厘米(cm)":
                        area = (float)(areaStandard * 2.54 * 2.54); break;
                    case "英寸(in)":
                        area = areaStandard; break;
                    case "米(m)":
                        area = (float)(areaStandard * 2.54 * 2.54 * 0.01 * 0.01); break;
                    case "毫米(mm)":
                        area = (float)(areaStandard * 2.54 * 2.54 * 10 * 10); break;
                }
                //改p数在这里改
                lblPhotoNum.Text = photoNum.ToString();
                lblProductArea.Text = string.Format("{0:0.##}", area);
            }
        }
        #endregion

        #region 按单位设置产品的高宽
        /// <summary>
        /// 按单位设置产品的高
        /// </summary>
        /// <param name="product"></param>
        private void SetProductHW()
        {
            float rh = (float)(Convert.ToDouble(spinHeight.Tag));
            float rw = (float)(Convert.ToDouble(spinWidth.Tag));
            float h = 0;
            float w = 0;
            string unit = cbUnit.Text;
            switch (unit)
            {
                case "厘米(cm)":
                    h = rh * (float)2.54;
                    w = rw * (float)2.54;
                    break;
                case "英寸(in)":
                    h = rh;
                    w = rw;
                    break;
                case "米(m)":
                    h = rh * (float)2.54 / 100;
                    w = rw * (float)2.54 / 100;
                    break;
                case "毫米(mm)":
                    h = rh * (float)2.54 * 10;
                    w = rw * (float)2.54 * 10;
                    break;
            }
            spinHeight.Text = string.Format("{0:0.##}", h);
            spinWidth.Text = string.Format("{0:0.##}", w);
            //SetMaxAndMin(h, w);                         //设置高宽的最大、最小范围
        }
        #endregion

        #region 修改高宽的事件
        //修改真实高
        private void spinHeight_Properties_Leave(object sender, EventArgs e)
        {
            try
            {
                if (currentProduct != null)
                {
                    float h = (float)Convert.ToDouble(spinHeight.Value);
                    string unit = cbUnit.Text;
                    float rh = 0;
                    switch (unit)
                    {
                        case "厘米(cm)":
                            rh = h / (float)2.54;
                            break;
                        case "英寸(in)":
                            rh = h;
                            break;
                        case "米(m)":
                            rh = h * 100 / (float)2.54;
                            break;
                        case "毫米(mm)":
                            rh = h / 10 / (float)2.54;
                            break;
                    }
                    spinHeight.Tag = rh;
                    SetPhotoNumAndArea(currentProduct.ProductTypeCode);        //计算照片总量与总面积 
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        //修改真实宽
        private void spinWidth_Properties_Leave(object sender, EventArgs e)
        {
            try
            {
                if (currentProduct != null)
                {
                    float h = (float)Convert.ToDouble(spinWidth.Value);
                    string unit = cbUnit.Text;
                    float rh = 0;
                    switch (unit)
                    {
                        case "厘米(cm)":
                            rh = h / (float)2.54;
                            break;
                        case "英寸(in)":
                            rh = h;
                            break;
                        case "米(m)":
                            rh = h * 100 / (float)2.54;
                            break;
                        case "毫米(mm)":
                            rh = h / 10 / (float)2.54;
                            break;
                    }
                    spinWidth.Tag = rh;
                    SetPhotoNumAndArea(currentProduct.ProductTypeCode);        //计算照片总量与总面积  
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
        #endregion

        //产品数量发生改变
        private void spinProductNum_Properties_Leave(object sender, EventArgs e)
        {
            try
            {
                if (currentProduct != null)
                    SetPhotoNumAndArea(currentProduct.ProductTypeCode);                  //参数需要改变
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        //产品Page数发生改变
        private void spinPageNum_Properties_Leave(object sender, EventArgs e)
        {
            try
            {
                if (currentProduct != null)
                    SetPhotoNumAndArea(currentProduct.ProductTypeCode);                  //参数需要改变
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        #region 点击"确定"，添加产品明细
        private void tsAddProduct_Click(object sender, EventArgs e)
        {
            SaveCurrentProduct();
        }
        #endregion

        #region 保存当前节点(在切换时或在开单时)
        /// <summary>
        /// 保存当前节点
        /// </summary>
        private void SaveCurrentProduct()
        {
            try
            {
                if (currentProduct == null)
                    return;
                //保存客户名称,下一个产品使用
                string preCtmName = txtCtmName.Text.Trim();
                Properties.Settings.Default.PreviousCtmName = preCtmName;
                Properties.Settings.Default.Save();

                //添加产品对象
                //currentProduct.Photos.Clear();
                currentProduct.ProductName = txtProductName.Text.Trim();
                currentProduct.CtmName = txtCtmName.Text;
                currentProduct.ProductNum = Convert.ToInt16(spinProductNum.Text.Trim());


                int ptypeID = 0;
                string ptypeName = cbPaperType.Text.Trim();
                foreach (StartOrderBLL.STPaperType ptype in ListPaperType)
                {
                    if (ptypeName == ptype.PaperTypeName)
                    {
                        ptypeID = ptype.PaperTypeID;
                        break;
                    }
                }
                //int pfaceID = 0;
                //string pfaceName = cbPaperFace.Text.Trim();
                //foreach (StartOrderBLL.STPaperFace pface in ListPaperFace)
                //{
                //    if (pfaceName == pface.PaperFaceName)
                //    {
                //        pfaceID = pface.PaperFaceID;
                //        break;
                //    }
                //}
                //currentProduct.PaperTypeID = ptypeID;
                //currentProduct.PaperFaceID = pfaceID;
                //currentProduct.PaperTypeName = ptypeName;
                //currentProduct.PaperFaceName = pfaceName;

                if (spinHeight.Tag == null)
                    spinHeight.Tag = 0;
                if (spinWidth.Tag == null)
                    spinWidth.Tag = 0;
                //打印机
                //currentProduct.OrilOrderPath = OrilOrderPath;
                if (currentProduct.ProductType != 1)                           //productType=1时，是新增产品实体，新实体没有流程
                    currentProduct.techs = singleProductTech;
                //currentProduct.ProductType = 3;                                                          //1实物  2产品模板  3二者都有


                // 如果产品需要设计
                if (currentProduct.ProductType != 1)// 只添加照片时不检查
                {
                    if (currentProduct.techs.FirstOrDefault(p => p.IsDesign && p.IsNeed) != null)//含有设计节点
                    {
                        if (!currentProduct.IsCheckStyle)
                        {

                            CheckSizeAndPage(currentProduct);
                        }

                    }
                }
                int intPageNum = Convert.ToInt32(spinPageNum.Text.Trim());
                //if (!ceProductWithoutPhoto.Checked)
                //{
                if (currentProduct.Photos != null && currentProduct.Photos.Count != 0 && intPageNum > currentProduct.Photos.Count)
                {
                    spinPageNum.Text = currentProduct.Photos.Count.ToString();
                }

                // }
                currentProduct.PageNum = Convert.ToInt32(spinPageNum.Text.Trim());

                currentProduct.Height = (float)Convert.ToDouble(string.Format("{0:0.##}", spinHeight.Tag));
                currentProduct.Width = (float)Convert.ToDouble(string.Format("{0:0.##}", spinWidth.Tag));
                currentProduct.Unit = cbUnit.Text.Trim();
                string remark = txtProductRemark.Text;
                string strSysMark = "*";//*标志是系统自动加


                foreach (MINERP.MODEL.CustomerManage.StartOrder.CommonChargeItemDDO ddo in AllCostItem)
                {
                    string targetValue = strSysMark + ddo.ItemName;
                    if (!string.IsNullOrEmpty(currentProduct.StringCostItems))
                    {
                        if (currentProduct.StringCostItems.Contains(ddo.ItemName))//
                        {
                            if (!remark.Contains(targetValue))
                            {
                                remark = targetValue + remark;
                            }
                            else
                            {
                                continue;
                            }

                        }
                        else
                        {
                            if (remark.Contains(targetValue))
                            {

                                int startIndex = remark.IndexOf(targetValue);
                                remark = remark.Remove(startIndex, targetValue.Length);
                            }
                            else
                            {
                                continue;
                            }
                        }
                    }
                    else
                    {
                        if (remark.Contains(targetValue))
                        {

                            int startIndex = remark.IndexOf(targetValue);
                            remark = remark.Remove(startIndex, targetValue.Length);
                        }
                        else
                        {
                            continue;
                        }
                    }

                }

                txtProductRemark.Text = remark;//将附加收费项目添加到备注


                currentProduct.ProductRemark = txtProductRemark.Text;

                currentProduct.PhotoNum = Convert.ToInt32(lblPhotoNum.Text);
                currentProduct.PhotoAllArea = (float)Convert.ToDouble(lblProductArea.Text);
                currentProduct.PrinterId = Convert.ToInt32(cbPrinter.SelectedValue);
                gcProductList.RefreshDataSource();
                //MessageBox.Show("成功设置产品信息", "确认", MessageBoxButtons.OK, MessageBoxIcon.Information);
                if (ceProductWithoutPhoto.Checked)
                {
                    currentProduct.ProductTypeCode = (int)OrderInfoProductType.NoPhotoProduct;
                }

                //清除产品明细
                //ClearProductDetail();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        private void SaveCurrentProductForOver()
        {
            try
            {
                if (currentProduct == null)
                    return;
                //保存客户名称,下一个产品使用
                string preCtmName = txtCtmName.Text.Trim();
                Properties.Settings.Default.PreviousCtmName = preCtmName;
                Properties.Settings.Default.Save();

                //添加产品对象
                //currentProduct.Photos.Clear();
                currentProduct.ProductName = txtProductName.Text.Trim();
                currentProduct.CtmName = txtCtmName.Text;
                currentProduct.ProductNum = Convert.ToInt16(spinProductNum.Text.Trim());


                int ptypeID = 0;
                string ptypeName = cbPaperType.Text.Trim();
                //foreach (StartOrderBLL.STPaperType ptype in ListPaperType)
                //{
                //    if (ptypeName == ptype.PaperTypeName)
                //    {
                //        ptypeID = ptype.PaperTypeID;
                //        break;
                //    }
                //}
                //int pfaceID = 0;
                //string pfaceName = cbPaperFace.Text.Trim();
                //foreach (StartOrderBLL.STPaperFace pface in ListPaperFace)
                //{
                //    if (pfaceName == pface.PaperFaceName)
                //    {
                //        pfaceID = pface.PaperFaceID;
                //        break;
                //    }
                //}
                //currentProduct.PaperTypeID = ptypeID;
                //currentProduct.PaperFaceID = pfaceID;
                //currentProduct.PaperTypeName = ptypeName;
                //currentProduct.PaperFaceName = pfaceName;

                if (spinHeight.Tag == null)
                    spinHeight.Tag = 0;
                if (spinWidth.Tag == null)
                    spinWidth.Tag = 0;
                //打印机
                //currentProduct.OrilOrderPath = OrilOrderPath;
                if (currentProduct.ProductType != 1)                           //productType=1时，是新增产品实体，新实体没有流程
                    currentProduct.techs = singleProductTech;
                //currentProduct.ProductType = 3;                                                          //1实物  2产品模板  3二者都有


                // 如果产品需要设计
                if (currentProduct.ProductType != 1)// 只添加照片时不检查
                {
                    if (currentProduct.techs.FirstOrDefault(p => p.IsDesign && p.IsNeed) != null)//含有设计节点
                    {
                        if (!currentProduct.IsCheckStyle)
                        {

                            CheckSizeAndPage(currentProduct);
                        }

                    }
                }
                int intPageNum = Convert.ToInt32(spinPageNum.Text.Trim());
                //if (!ceProductWithoutPhoto.Checked)
                //{
                if (currentProduct.Photos != null && currentProduct.Photos.Count != 0 && intPageNum > currentProduct.Photos.Count)
                {
                    spinPageNum.Text = currentProduct.Photos.Count.ToString();
                }

                // }
                currentProduct.PageNum = Convert.ToInt32(spinPageNum.Text.Trim());

                currentProduct.Height = (float)Convert.ToDouble(string.Format("{0:0.##}", spinHeight.Tag));
                currentProduct.Width = (float)Convert.ToDouble(string.Format("{0:0.##}", spinWidth.Tag));
                currentProduct.Unit = cbUnit.Text.Trim();
                string remark = txtProductRemark.Text;
                string strSysMark = "*";//*标志是系统自动加


                foreach (MINERP.MODEL.CustomerManage.StartOrder.CommonChargeItemDDO ddo in AllCostItem)
                {
                    string targetValue = strSysMark + ddo.ItemName;
                    if (!string.IsNullOrEmpty(currentProduct.StringCostItems))
                    {
                        if (currentProduct.StringCostItems.Contains(ddo.ItemName))//
                        {
                            if (!remark.Contains(targetValue))
                            {
                                remark = targetValue + remark;
                            }
                            else
                            {
                                continue;
                            }

                        }
                        else
                        {
                            if (remark.Contains(targetValue))
                            {

                                int startIndex = remark.IndexOf(targetValue);
                                remark = remark.Remove(startIndex, targetValue.Length);
                            }
                            else
                            {
                                continue;
                            }
                        }
                    }
                    else
                    {
                        if (remark.Contains(targetValue))
                        {

                            int startIndex = remark.IndexOf(targetValue);
                            remark = remark.Remove(startIndex, targetValue.Length);
                        }
                        else
                        {
                            continue;
                        }
                    }

                }

                txtProductRemark.Text = remark;//将附加收费项目添加到备注


                currentProduct.ProductRemark = txtProductRemark.Text;

                currentProduct.PhotoNum = Convert.ToInt32(lblPhotoNum.Text);
                currentProduct.PhotoAllArea = (float)Convert.ToDouble(lblProductArea.Text);
                currentProduct.PrinterId = Convert.ToInt32(cbPrinter.SelectedValue);
                gcProductList.RefreshDataSource();
                //MessageBox.Show("成功设置产品信息", "确认", MessageBoxButtons.OK, MessageBoxIcon.Information);
                if (ceProductWithoutPhoto.Checked)
                {
                    currentProduct.ProductTypeCode = (int)OrderInfoProductType.NoPhotoProduct;
                }

                //清除产品明细
                //ClearProductDetail();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region 取消当前正在编辑的产品
        private void tsRemove_Click(object sender, EventArgs e)
        {
            try
            {
                if (ListProduct == null || ListProduct.Count == 0)
                    return;
                foreach (StartOrderBLL.ProductInfo product in ListProduct)
                {
                    if (product.ProductSerialID == currentSerialID)
                    {
                        ListProduct.Remove(product);
                        gcProductList.RefreshDataSource();
                        break;
                    }
                }
                //清除产品明细
                ClearProductDetail();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
        #endregion

        #region "切换"按钮
        bool DisplayMode = false;   //false列表  true缩略图 //如果照片是TIF，可能会出错
        RasterThumbnailBrowser browser;
        //"切换"按钮
        private void tsExchange_Click(object sender, EventArgs e)
        {
            try
            {
                Cursor = Cursors.WaitCursor;
                if (DisplayMode == false)       //当前是列表,点击后以缩略图显示
                {
                    if (PhotoAndThumbList == null)
                        return;
                    RasterCodecs.Startup();
                    RasterCodecs codecs = new RasterCodecs();
                    foreach (PhotoListAndThumb pat in PhotoAndThumbList)
                    {
                        if (pat.ThumbIsAdded == false)      //还未加载缩略图
                        {
                            File.SetAttributes(pat.Item.PhotoFullPath, FileAttributes.Normal);
                            CodecsThumbnailOptions options = new CodecsThumbnailOptions();
                            options.Resample = true;
                            options.LoadStamp = true;
                            options.MaintainAspectRatio = true;
                            RasterImage img = null;
                            try
                            {
                                //img = codecs.ReadThumbnail(pat.Item.PhotoFullPath, options, 1);
                                img = codecs.ReadStamp(pat.Item.PhotoFullPath, 1);
                            }
                            catch       //如果缩略图不存在，设置缩略图
                            {
                                string pattern = pat.Item.PhotoFullPath.Substring(pat.Item.PhotoFullPath.LastIndexOf("." + 1));
                                RasterImage imgInfo = codecs.Load(pat.Item.PhotoFullPath);
                                Rectangle rec = RasterImage.CalculatePaintModeRectangle(imgInfo.Width, imgInfo.Height, new Rectangle(0, 0, 128, 128), RasterPaintSizeMode.FitAlways, RasterPaintAlignMode.Near, RasterPaintAlignMode.Near);

                                switch (pattern)
                                {
                                    case "jpg":
                                        codecs.Options.Jpeg.Save.StampHeight = rec.Height;
                                        codecs.Options.Jpeg.Save.StampWidth = rec.Width;
                                        codecs.Options.Jpeg.Save.SaveWithStamp = true;
                                        codecs.Options.Jpeg.Save.StampBitsPerPixel = 24;
                                        codecs.Save(imgInfo, pat.Item.PhotoFullPath, RasterImageFormat.Jpeg, 0);
                                        img = codecs.ReadThumbnail(pat.Item.PhotoFullPath, options, 1);
                                        break;
                                    case "tif":
                                        MessageBox.Show("Tif文件目前不支持缩略图");
                                        break;
                                }

                            }
                            if (img == null)//如果为空就加载原图
                            {
                                img = codecs.Load(pat.Item.PhotoFullPath);
                                //return;
                            }
                            RasterImageListItem thumb = new RasterImageListItem(img, 1, pat.Item.PhotoName);
                            thumb.Tag = pat.Item.PhotoFullPath;
                            browser.Items.Add(thumb);
                            pat.Thumb = thumb;
                            pat.ThumbIsAdded = true;
                        }
                    }
                    codecs.Dispose();
                    RasterCodecs.Shutdown();
                    TongBu();
                    //移除列表对象,加载缩略图对象
                    spcProductDetail.Panel2.Controls.Clear();
                    spcProductDetail.Panel2.Controls.Add(browser);
                    browser.DoubleClick += new EventHandler(browser_DoubleClick);
                }
                else        //当前是缩略图,点击后以列表显示
                {
                    //移除缩略图对象,加载列表对象
                    spcProductDetail.Panel2.Controls.Clear();
                    spcProductDetail.Panel2.Controls.Add(gcProduct);
                    TongBu();
                }
                //同步
                DisplayMode = DisplayMode == true ? false : true;
                Cursor = Cursors.Default;
            }
            catch (Exception ex)
            {
                Cursor = Cursors.Default;
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        //双击缩略图浏览大图
        void browser_DoubleClick(object sender, EventArgs e)
        {
            try
            {
                Cursor = Cursors.WaitCursor;
                RasterThumbnailBrowser b = sender as RasterThumbnailBrowser;
                string selectedPath = b.SelectedItems[0].Tag.ToString();
                //浏览大图
                List<string> photoPaths = new List<string>();
                int currentIndex = 0;
                foreach (RasterImageListItem item in b.Items)
                {
                    photoPaths.Add(item.Tag.ToString());
                    photoPaths.Add("");
                }
                for (int i = 0; 2 * i < photoPaths.Count; i++)
                {
                    if (selectedPath == photoPaths[2 * i])
                    {
                        currentIndex = 2 * i;
                        break;
                    }
                }
                ComControls.BigPicViewer bpv = new MINERP.ComControls.BigPicViewer();
                bpv.PhotoPaths = photoPaths;
                bpv.CurrentIndex = currentIndex / 2;
                bpv.ShowDialog();
                Cursor = Cursors.Default;
            }
            catch (Exception ex)
            {
                Cursor = Cursors.Default;
                MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 切换时，缩略图和列表的同步操作(同步操作有问题)
        /// </summary>
        private void TongBu()
        {
            if (DisplayMode == false)          //当前显示的是列表
            {
                int[] indexes = gvProduct.GetSelectedRows();
                List<StartOrderBLL.STPhoto> TBPhotos = new List<StartOrderBLL.STPhoto>();
                foreach (int index in indexes)
                {
                    StartOrderBLL.STPhoto photo = gvProduct.GetRow(index) as StartOrderBLL.STPhoto;
                    TBPhotos.Add(photo);
                }
                foreach (PhotoListAndThumb pat in PhotoAndThumbList)
                {
                    bool isIn = false;
                    foreach (StartOrderBLL.STPhoto photo in TBPhotos)
                    {
                        if (pat.Item == photo)
                        {
                            isIn = true;
                            pat.Thumb.Selected = true;
                            break;
                        }
                    }
                    if (isIn == false)
                    {
                        pat.Thumb.Selected = false;
                    }
                }
            }
            else                                //当前显示的是缩略图
            {
                RasterImageListItemCollection thumbs = browser.SelectedItems;
                gvProduct.ClearSelection();
                foreach (PhotoListAndThumb pat in PhotoAndThumbList)
                {
                    if (pat.Thumb.Selected == true)
                    {
                        StartOrderBLL.STPhoto photo = pat.Item;
                        int srcIndex = currentProduct.Photos.IndexOf(photo);           //在数据源中的索引
                        int index = gvProduct.GetRowHandle(srcIndex);
                        gvProduct.SelectRow(index);
                    }
                }
            }
        }
        #endregion

        #region 按Del键删除照片
        //删除列表
        private void gvProduct_KeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                int[] delIndexes = gvProduct.GetSelectedRows();
                if (e.KeyData == Keys.Delete && delIndexes.Length > 0)
                {

                    DeletePhoto(delIndexes);
                    gcProduct.RefreshDataSource();
                    gvProduct.ClearSelection();
                }
                SetPhotoNumAndArea(currentProduct.ProductTypeCode);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
        //删除缩略图
        void browser_KeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                if (e.KeyData == Keys.Delete)
                {
                    RasterImageListItemCollection thumbs = browser.SelectedItems;
                    if (thumbs == null || thumbs.Count == 0)
                        return;
                    DeletePhotoThumb(thumbs);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
        #endregion

        #region "删除"照片按钮
        //"删除"按钮
        private void tsDeletePhoto_Click(object sender, EventArgs e)
        {
            try
            {
                if (currentProduct == null || currentProduct.Photos == null || currentProduct.Photos.Count == 0 || gvProduct.SelectedRowsCount == 0)
                    return;
                if (DisplayMode == false)                              //从缩略图删除
                {
                    if (gvProduct.DataSource != null)
                    {
                        int[] delIndexes = gvProduct.GetSelectedRows();
                        DeletePhoto(delIndexes);
                    }
                }
                else
                {
                    RasterImageListItemCollection thumbs = browser.SelectedItems;
                    DeletePhotoThumb(thumbs);
                }
                gcProduct.RefreshDataSource();
                gvProduct.ClearSelection();
                SetPhotoNumAndArea(currentProduct.ProductTypeCode);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
        #endregion

        #region 删除照片
        /// <summary>
        /// 删除照片(从列表删除)
        /// </summary>
        private void DeletePhoto(int[] delIndexes)
        {
            try
            {
                if (DialogResult.Yes == MessageBox.Show("确定要删除吗?", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Warning))
                {
                    //要删除的照片集合
                    List<StartOrderBLL.STPhoto> TempDelPhots = new List<StartOrderBLL.STPhoto>();
                    foreach (int index in delIndexes)
                    {
                        StartOrderBLL.STPhoto photo = gvProduct.GetRow(index) as StartOrderBLL.STPhoto;
                        TempDelPhots.Add(photo);
                    }
                    foreach (StartOrderBLL.STPhoto photo in TempDelPhots)
                    {
                        currentProduct.Photos.Remove(photo);                    //从列表移除
                        //从显示的大对象删除
                        foreach (PhotoListAndThumb pat in PhotoAndThumbList)
                        {
                            if (pat.Item == photo)
                            {
                                browser.Items.Remove(pat.Thumb);        //从缩略图移除
                                PhotoAndThumbList.Remove(pat);          //从大对象移除
                                break;
                            }
                        }
                    }

                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
        /// <summary>
        /// 删除照片(从缩略图删除)
        /// </summary>
        /// <param name="thumbs"></param>
        private void DeletePhotoThumb(RasterImageListItemCollection thumbs)
        {
            if (DialogResult.Yes == MessageBox.Show("确定要删除吗?", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Warning))
            {
                foreach (RasterImageListItem thumb in thumbs)
                {
                    foreach (PhotoListAndThumb pat in PhotoAndThumbList)
                    {
                        if (pat.Thumb == thumb)
                        {
                            browser.Items.Remove(thumb);            //从缩略图移除
                            currentProduct.Photos.Remove(pat.Item);         //从列表移除
                            PhotoAndThumbList.Remove(pat);          //从大对象移除
                            break;
                        }
                    }
                }
            }
        }
        #endregion

        #region 添加产品明细后，清除该产品明细
        /// <summary>
        /// 添加产品明细后，清除该产品明细
        /// </summary>
        private void ClearProductDetail()
        {
            txtProductName.Text = "";
            spinProductNum.Text = "1";
            spinWidth.Text = "1";
            spinHeight.Text = "1";
            spinPageNum.Text = "1";
            txtProductRemark.Text = "";
            lblPhotoNum.Text = "0";
            lblProductArea.Text = "0";
            //cbPaperFace.Text = "";
            //cbPaperType.Text = "";
            cbPrinter.SelectedValue = 0;
            if (DisplayMode == true)
            {
                spcProductDetail.Panel2.Controls.Clear();
                spcProductDetail.Panel2.Controls.Add(gcProduct);
                DisplayMode = false;
            }
            if (pProductFlow.Controls != null)
                pProductFlow.Controls.Clear();
            gcProduct.DataSource = null;
        }
        #endregion

        #region 需要重新设置照片数量与面积的地方
        //产品份数发生改变时
        private void spinProductNum_EditValueChanged(object sender, EventArgs e)
        {
            try
            {
                if (currentProduct != null)
                {
                    SetPhotoNumAndArea(currentProduct.ProductTypeCode);                    //设置照片数量与面积
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        //Page数发生改变时
        private void spinPageNum_EditValueChanged(object sender, EventArgs e)
        {
            try
            {
                if (currentProduct != null)
                {
                    SetPhotoNumAndArea(currentProduct.ProductTypeCode);                    //设置照片数量与面积
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        //高改变时
        private void spinHeight_EditValueChanged(object sender, EventArgs e)
        {
            try
            {
                if (currentProduct != null)
                {
                    SetPhotoNumAndArea(currentProduct.ProductTypeCode);                    //设置照片数量与面积
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        //宽改变时
        private void spinWidth_EditValueChanged(object sender, EventArgs e)
        {
            try
            {
                if (currentProduct != null)
                {
                    SetPhotoNumAndArea(currentProduct.ProductTypeCode);                    //设置照片数量与面积
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
        #endregion

        #region 关闭窗体前，若订单包并没有开，删除先前生成的占位订单包
        private void FrmStartOrder_FormClosing(object sender, FormClosingEventArgs e)
        {
            try
            {
                Cursor = Cursors.WaitCursor;
                //关闭tcp连接
                if (clientSocket != null && clientSocket.Connected)
                {
                    int r = CrcCheck(currentProduct, "close");
                    clientSocket.Close();
                }
                if (client != null && client.Connected)
                {
                    client.Close();
                }
                if (IsOpenedOrder == false)
                {
                    //删除占位的订单
                    SOBLL.DelOrderBagTemp(OrderID);
                }
                //线程获取开单树
                IsOpenStartOrder = false;       //关闭后，是否已实例化开单页面就为false
                IsGetTree = false;              //同时是否已获取开单树也为false，需要重新获取
                Manage.ThreadGetTree();
                Cursor = Cursors.Default;
            }
            catch (Exception ex)
            {
                Cursor = Cursors.Default;
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            Manage.StartOrderNum = 0;       //开单页面数为0
        }
        #endregion

        #region 用照片数量设置Page数
        //用照片数量设置Page数
        private void lblPhotoNum_TextChanged(object sender, EventArgs e)
        {

            if (currentProduct != null && !currentProduct.IsNeedDesign)
            {
                spinPageNum.Text = lblPhotoNum.Text.ToString();
            }
        }
        #endregion

        //-----------------------------------------------
        //----------产品明细操作结束---------------------
        //-----------------------------------------------

        //-----------------------------------------------
        //-------------左边目录树的操作------------------
        //-----------------------------------------------
        public float ModifyPhotoHeight { get; set; }    //修改后照片的高
        public float ModifyPhotoWidth { get; set; }     //修改后照片的宽

        TreeNode currentNode;                           //当前正在操作的节点,用于设置已开单产品的背景色

        #region 待开单目录结构
        //委托

        /// <summary>
        /// 待开单订单的目录
        /// </summary>
        private void AddStartOrderPath()            //从磁盘加载
        {
            try
            {
                //等待开单目录结构思想：
                //商户层固定，每个商户下“已开单”临时目录固定
                //1 客户层中只有照片，就形成一个产品，产品名从右边获取
                //2 客户层中有照片和目录，提示有照片和目录同时存在，是否要继续开单，如果是，就形成一个产品，产品名从右边获取
                //3 客户层中只有目录，按三层结构开单
                //----------------------------------------
                tvOrderPath.Nodes.Clear();                                  //清除原有的节点
                //string totalPath = @"D:\HW\开单测试目录";                   //开单总目录应从配置文件中获得
                string totalPath = TotalPath;
                string directoryName = totalPath.Substring(totalPath.LastIndexOf("\\") + 1);
                if (directoryName != "等待开单")
                    MessageBox.Show("等待开单的目录设置不正确，请在后台重新设置！", "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                totalPath += "\\" + UserName;                                   //每个开单员只能操作本人文件夹内的待开单文件
                string[] directorys = Directory.GetDirectories(totalPath);
                foreach (string directory in directorys)
                {
                    if (IsEmpty(directory, true))
                        continue;
                    if (Directory.GetDirectories(directory).Length > 1)
                    {
                        DirectoryInfo directoryInfo = new DirectoryInfo(directory);
                        TreeNode node = new TreeNode(directoryInfo.Name);           //商户层 最后一位1表示处于第一层
                        node.Name = directoryInfo.Name + "1";
                        node.Tag = directoryInfo.FullName;
                        //node.ImageIndex = 1;
                        tvOrderPath.Nodes.Add(node);
                        string[] subDirectorys = Directory.GetDirectories(directory);
                        foreach (string subDirectory in subDirectorys)
                        {
                            if (IsEmpty(subDirectory, false))
                                continue;
                            DirectoryInfo subInfo = new DirectoryInfo(subDirectory);
                            if (subInfo.Name != "已开单")
                            {
                                TreeNode subNode = new TreeNode(subInfo.Name);
                                subNode.Name = subInfo.Name + "2";                  //客户层，最后一位2表示处于第二层
                                subNode.Tag = subInfo.FullName;
                                //subNode.ImageIndex = 0;
                                node.Nodes.Add(subNode);
                              
                                string[] ssubFiles = GetFilesPath(subDirectory);

                                if (ssubFiles.Length > 0)                           //如果客户目录里有照片，就不再加载产品
                                    continue;
                                string[] ssubDirectorys = Directory.GetDirectories(subDirectory);
                                if (ssubDirectorys.Length == 0)                     //如果客户目录里没有子目录，就不再加载产品               
                                    continue;
                                foreach (string ssubDirectory in ssubDirectorys)
                                {
                                    if (IsEmpty(ssubDirectory, false))
                                        continue;
                                    DirectoryInfo ssubInfo = new DirectoryInfo(ssubDirectory);
                             
                                    FileInfo[] sssfiles = GetFileInfo(ssubDirectory);
                                    DirectoryInfo[] sssdirectorys = ssubInfo.GetDirectories();
                                    if (sssfiles.Count() == 0 && sssdirectorys.Count() == 0)
                                        continue;
                                    TreeNode ssubNode = new TreeNode(ssubInfo.Name);
                                    ssubNode.Name = ssubInfo.Name + "3";            //产品层，最后一位3表示处于第三层
                                    ssubNode.Tag = ssubInfo.FullName;
                                    subNode.Nodes.Add(ssubNode);
                                    //ssubNode.ImageIndex = 0;

                                    //产品内不同尺寸目录
                                    foreach (DirectoryInfo sssdirectory in sssdirectorys)
                                    {
                                        TreeNode sssubNode = new TreeNode(sssdirectory.Name);
                                        sssubNode.Name = sssdirectory.Name + "4";
                                        sssubNode.Tag = sssdirectory.FullName;
                                        ssubNode.Nodes.Add(sssubNode);
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确定", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
        private void AddStartOrderPath2()       //从内存加载
        {
            try
            {
                //等待开单目录结构思想：
                //商户层固定，每个商户下“已开单”临时目录固定
                //1 客户层中只有照片，就形成一个产品，产品名从右边获取
                //2 客户层中有照片和目录，提示有照片和目录同时存在，是否要继续开单，如果是，就形成一个产品，产品名从右边获取
                //3 客户层中只有目录，按三层结构开单
                //----------------------------------------
                tvOrderPath.Nodes.Clear();                                      //清除原有的节点
                //string totalPath = @"D:\HW\开单测试目录";                     //开单总目录应从配置文件中获得
                foreach (StartOrderBLL.OrderTree t in FrmManage.Tree)
                {
                    TreeNode node = new TreeNode(t.ShopText);                   //商户层
                    node.Name = t.ShopName;                                     //已加上层次结构1
                    node.Tag = t.ShopFullName;
                    tvOrderPath.Nodes.Add(node);
                    foreach (StartOrderBLL.OrderCtm c in t.Ctms)
                    {
                        TreeNode subNode = new TreeNode(c.CtmText);             //客户层
                        subNode.Name = c.CtmName;                               //已加上层次结构2
                        subNode.Tag = c.CtmFullName;
                        //subNode.ImageIndex = 0;
                        node.Nodes.Add(subNode);
                        foreach (StartOrderBLL.OrderProduct p in c.Products)
                        {
                            TreeNode ssubNode = new TreeNode(p.ProductText);    //产品层
                            ssubNode.Name = p.ProductName;                      //已加上层次结构3
                            ssubNode.Tag = p.ProductFullName;
                            subNode.Nodes.Add(ssubNode);
                            //ssubNode.ImageIndex = 0;

                            foreach (StartOrderBLL.ProductCC cc in p.Ccs)       //产品内的不同尺寸目录
                            {
                                TreeNode sssubNode = new TreeNode(cc.CCText);
                                sssubNode.Name = cc.CCName;
                                sssubNode.Tag = cc.CCFullName;
                                ssubNode.Nodes.Add(sssubNode);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确定", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }/// <summary>
        /// 加载开单树
        /// </summary>
        public void GetTree()
        {
            try
            {
                FrmManage.Tree.Clear();
                //等待开单目录结构思想：
                //商户层固定，每个商户下“已开单”临时目录固定
                //1 客户层中只有照片，就形成一个产品，产品名从右边获取
                //2 客户层中有照片和目录，提示有照片和目录同时存在，是否要继续开单，如果是，就形成一个产品，产品名从右边获取
                //3 客户层中只有目录，按三层结构开单
                //----------------------------------------
                string totalPath = SOBLL.GetStartOrderPath();
                string directoryName = totalPath.Substring(totalPath.LastIndexOf("\\") + 1);
                if (directoryName != "等待开单")
                    MessageBox.Show("等待开单的目录设置不正确，请在后台重新设置！", "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                totalPath += "\\" + UserName;                                   //每个开单员只能操作本人的开单文件夹
                string[] directorys = Directory.GetDirectories(totalPath);
                foreach (string directory in directorys)
                {
                    if (IsEmpty(directory, true))
                        continue;
                    if (Directory.GetDirectories(directory).Length > 1)
                    {
                        DirectoryInfo directoryInfo = new DirectoryInfo(directory);
                        StartOrderBLL.OrderTree ot = new StartOrderBLL.OrderTree();
                        ot.ShopName = directoryInfo.Name + "1";                     //商户层，最后一位1表示处于第一层
                        ot.ShopText = directoryInfo.Name;
                        ot.ShopFullName = directoryInfo.FullName;
                        FrmManage.Tree.Add(ot);

                        string[] subDirectorys = Directory.GetDirectories(directory);
                        foreach (string subDirectory in subDirectorys)
                        {
                            if (IsEmpty(subDirectory, false))
                                continue;
                            DirectoryInfo subInfo = new DirectoryInfo(subDirectory);
                            if (subInfo.Name != "已开单")
                            {
                                StartOrderBLL.OrderCtm oc = new StartOrderBLL.OrderCtm();
                                oc.CtmName = subInfo.Name + "2";                    //客户层，最后一位2表示处于第二层
                                oc.CtmText = subInfo.Name;
                                oc.CtmFullName = subInfo.FullName;
                                ot.Ctms.Add(oc);

                              
                                string[] ssubFiles = GetFilesPath(subDirectory);
                                if (ssubFiles.Length > 0)                           //如果客户目录里有照片，就不再加载产品
                                    continue;
                                string[] ssubDirectorys = Directory.GetDirectories(subDirectory);
                                if (ssubDirectorys.Length == 0)                     //如果客户目录里没有子目录，就不再加载产品               
                                    continue;
                                foreach (string ssubDirectory in ssubDirectorys)
                                {
                                    if (IsEmpty(ssubDirectory, false))
                                        continue;
                                    DirectoryInfo ssubInfo = new DirectoryInfo(ssubDirectory);
                        
                                    FileInfo[] sssfiles = GetFileInfo(ssubDirectory);
                                    DirectoryInfo[] sssdirectorys = ssubInfo.GetDirectories();
                                    if (sssfiles.Count() == 0 && sssdirectorys.Count() == 0)
                                        continue;
                                    StartOrderBLL.OrderProduct op = new StartOrderBLL.OrderProduct();
                                    op.ProductName = ssubInfo.Name + "3";           //产品层，最后一位3表示处于第三层
                                    op.ProductText = ssubInfo.Name;
                                    op.ProductFullName = ssubInfo.FullName;
                                    oc.Products.Add(op);

                                    foreach (DirectoryInfo sssDirectory in sssdirectorys)
                                    {
                                        StartOrderBLL.ProductCC cc = new StartOrderBLL.ProductCC();
                                        cc.CCName = sssDirectory.Name + "4";
                                        cc.CCText = sssDirectory.Name;
                                        cc.CCFullName = sssDirectory.FullName;
                                        op.Ccs.Add(cc);
                                    }
                                }
                            }
                        }
                    }
                }
                FrmStartOrder.IsGetTree = true;

            }
            catch (Exception ex)
            {
                if (ex is ThreadAbortException)
                { }
            }
        }

        //指定的目录是否是空的
        public bool IsEmpty(string directory, bool isShop)
        {
            try
            {
                if (isShop == true)         //商户节点
                {
                    string[] subDirectorys = Directory.GetDirectories(directory);
                    if (subDirectorys.Length == 1)
                        return true;
                    else
                    {
                        foreach (string subDirectory in subDirectorys)
                        {
                            if (!IsEmpty(subDirectory, false))
                                return false;
                        }
                        return true;
                    }
                }
                else
                {
                    try
                    {
                        string[] subFiles = GetFilesPath(directory);
                        string[] subDirectorys = Directory.GetDirectories(directory);
                        if (subFiles.Length > 0)
                            return false;
                        foreach (string subDirectory in subDirectorys)
                        {
                            if (!IsEmpty(subDirectory, false))
                                return false;
                        }
                        return true;
                    }
                    catch (Exception exx)
                    {

                        MessageBox.Show("请检查 ”"+directory+"“目录。如果有空格结尾，请将空格去掉后刷新", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return false;
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 删除已开掉单的产品节点
        /// </summary>
        /// <param name="shopPath"></param>
        private void RefreshStartOrderPath()
        {
            try
            {
                foreach (TreeNode node in tvOrderPath.Nodes)
                {
                    if (node.Tag.ToString() == currentShopPath)
                    {
                        node.Nodes.Clear();
                        string[] subDirectorys = Directory.GetDirectories(currentShopPath);
                        foreach (string subDirectory in subDirectorys)
                        {
                            DirectoryInfo subInfo = new DirectoryInfo(subDirectory);
                            if (subInfo.Name != "已开单")
                            {
                                TreeNode subNode = new TreeNode(subInfo.Name);
                                subNode.Name = subInfo.Name + "2";
                                subNode.Tag = subInfo.FullName;
                                node.Nodes.Add(subNode);
                                string[] ssubDirectorys = Directory.GetDirectories(subDirectory);
                                foreach (string ssubDirectory in ssubDirectorys)
                                {
                                    DirectoryInfo ssubInfo = new DirectoryInfo(ssubDirectory);
                                    TreeNode ssubNode = new TreeNode(ssubInfo.Name);
                                    ssubNode.Name = ssubInfo.Name + "3";
                                    ssubNode.Tag = ssubInfo.FullName;
                                    subNode.Nodes.Add(ssubNode);
                                    //ssubNode.ImageIndex = 0;
                                }
                            }
                        }
                        if (node.Nodes == null || node.Nodes.Count == 0)//删除节点本身
                        {
                            tvOrderPath.Nodes.Remove(node);
                        }
                        return;
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region 拖曳产品实体或客户
        //开始拖曳产品或客户
        private void tvOrderPath_ItemDrag(object sender, ItemDragEventArgs e)
        {
            try
            {
                TreeNode node = e.Item as TreeNode;
                if (node.Parent == null)                                        //商户节点不可拖曳
                {
                    return;
                }
                if (node.BackColor == Color.Pink)
                {
                    MessageBox.Show("客户或产品已开过单，不能再开！", "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                currentNode = node;
                List<string> productPaths = new List<string>();
                string cc = node.Name.Substring(node.Name.Length - 1);
                //目录是否为空
                if (IsEmpty(node.Tag.ToString(), false))
                {
                    MessageBox.Show("目录为空！", "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    DelTreeNode(node);
                    return;
                }
                if (cc == "4")                                          //产品内不同的尺寸目录不能拖曳
                {
                    return;
                }
                if (cc == "3")                                         //产品节点 3表示处于第三层，也就是产品层
                {
                    //产品实体
                    string shopPath = node.Parent.Parent.Tag.ToString();
                    if (currentShopPath != "" && shopPath != currentShopPath && ListProduct != null && ListProduct.Count > 0)
                    {
                        MessageBox.Show("只有相同的商户才能开一个订单！", "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        return;
                    }
                    DragType = 2;
                    productPaths.Add(node.Tag.ToString());
                    currentShopPath = shopPath;                                 //商户路径，开单后刷新使用
                }
                else                                                            //客户节点
                {
                    string shopPath = node.Parent.Tag.ToString();
                    if (currentShopPath != "" && shopPath != currentShopPath)
                    {
                        MessageBox.Show("只有相同的商户才能开一个订单！", "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        return;
                    }
                    if (node.Nodes == null || node.Nodes.Count == 0)
                    {
                        //客户层内没有产品节点
                        string ctmPath = node.Tag.ToString();
                        productPaths.Add(ctmPath);      //将客户目录作为单位开单
                        DragType = 4;
                    }
                    else
                    {
                        DragType = 1;                       //客户实体
                        foreach (TreeNode n in node.Nodes)
                        {
                            productPaths.Add(n.Tag.ToString());
                        }
                    }
                    currentShopPath = shopPath;                                       //商户路径，开单后刷新使用
                }
                DataObject data = new DataObject();
                data.SetData("list", productPaths);
                DoDragDrop(data, DragDropEffects.All);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
        #endregion

        #region 删除节点
        /// <summary>
        /// 删除节点
        /// </summary>
        /// <param name="node"></param>
        private void DelTreeNode(TreeNode node)
        {
            try
            {
                TreeNode parentNode = node.Parent;
                node.Remove();
                if (parentNode != null && (parentNode.Nodes == null || parentNode.Nodes.Count == 0))
                    DelTreeNode(parentNode);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region 将产品实体匹配模板
        /// <summary>
        /// 将产品实体匹配模板
        /// </summary>
        private void AddProductOnModel(string productPath)
        {
            if (DisplayMode == true)
            {
                spcProductDetail.Panel2.Controls.Clear();
                spcProductDetail.Panel2.Controls.Add(gcProduct);
                DisplayMode = false;
            }
            if (pProductFlow.Controls != null)
                pProductFlow.Controls.Clear();
            DirectoryInfo productInfo, ctmInfo, shopInfo;
            string productRemark;
            if (DragType == 4)                 //客户目录指定的产品实体
            {
                ctmInfo = new DirectoryInfo(productPath);
                shopInfo = ctmInfo.Parent;
                productRemark = ctmInfo.Name;
            }
            else
            {
                productInfo = new DirectoryInfo(productPath);
                ctmInfo = productInfo.Parent;
                shopInfo = ctmInfo.Parent;
                productRemark = productInfo.Name;
            }
            //商户名称
            string shopName = shopInfo.Name;
            /*
            DirectoryInfo productInfo = new DirectoryInfo(productPath);
            DirectoryInfo ctmInfo = productInfo.Parent;
            DirectoryInfo shopInfo = ctmInfo.Parent;
            //商户名称
            string shopName = shopInfo.Name;*/
            int shopId = getShopId(shopName);
            if (shopId == 0)
            {
                MessageBox.Show("当前商户不存在,请在后台添加!", "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            //客户名称
            string ctmName = ctmInfo.Name;
            //加载产品照片
            AddPhotosOfProduct(productPath);
            currentProduct.ProductType = 3;                                             //1实体  2产品模板  3二者综合
            //匹配客户名称，商户名称，纸型，纸面,产品备注
            int index1 = productPath.LastIndexOf("\\");
            string path1 = productPath.Substring(0, index1);
            int index2 = path1.LastIndexOf("\\");
            string path2 = path1.Substring(0, index2);
            string path3 = productPath.Substring(index2 + 1);
            string orilPath = path2 + "\\" + "已开单" + "\\" + path3;
            currentProduct.OrilOrderPath = orilPath;
            currentProduct.CtmName = ctmName;
            txtOrderName.Text = ctmName;
            txtCtmName.Text = ctmName;
            cbShopName.Text = shopName;
            //txtShopRequire.Text = productRemark;
            currentProduct.ProductRemark = productRemark;
            currentProduct.CtmName = ctmName;
            //产品名称
            currentProduct.ProductName = productRemark + "_" + currentProduct.ProductName;
            txtProductRemark.Text = productRemark;
            txtProductName.Text = currentProduct.ProductName;
            //产品备注加上商户的备注
            txtProductRemark.Text += "\\" + txtShopRequire.Text;
            currentProduct.ProductRemark = txtProductRemark.Text;
            //根据商户名称设置商户特有产品
            cbShopName_SelectedIndexChanged(new object(), new EventArgs());

            //保存产品的原路径，在移动时使用
            currentProduct.OrilOrderPath2 = productPath;

            //设置产品照片数量与总面积
            SetPhotoNumAndArea(currentProduct.ProductTypeCode);                          //参数需要改变
            MINERP.BLL.CustomerManage.StartOrderBLL.STProductTech stTech = currentProduct.techs.FirstOrDefault(p => p.IsDesign);
            if (currentProduct.ProductTypeCode == (int)OrderInfoProductType.NeedDesignPrint || currentProduct.ProductTypeCode == (int)OrderInfoProductType.NeedDesignProduct || currentProduct.ProductTypeCode == (int)OrderInfoProductType.NeedDesignKuoYin)
            {
                if (!currentProduct.IsCheckStyle)
                {

                    CheckSizeAndPage(currentProduct);//确认大小和page数
                    if (stTech.IsNeed)
                    { 
                        currentProduct.StringCostItems = stTech.CommonChargeItems;//添加设计节点附带的收费项目
                    }
                }
            }
            //11.11.22更新产品的附加收费
            foreach (ProductCommonItem pci in currentProduct.ProductCommonBing)
            {

                if (AllCostItem.FirstOrDefault(pi => pi.CommonChargeItemId == pci.CommonID) != null)
                {
                    currentProduct.StringCostItems += "," + pci.ItemName;

                }
            }
            currentProduct.StringCostItems = currentProduct.StringCostItems.TrimEnd(',');
        }
        #endregion



        #region 加载产品实体的照片
        /// <summary>
        /// 加载产品实体的照片
        /// </summary>
        /// <param name="productPath"></param>
        private void AddPhotosOfProduct(string productPath)
        {
            List<string> photoPaths = new List<string>();
            GetPhotoPathsOfProduct(photoPaths, productPath);                            //获取产品实体的所有照片
            string[] photoPaths2 = new string[photoPaths.Count];
            for (int i = 0; i < photoPaths.Count; i++)
            {
                photoPaths2[i] = photoPaths[i];
            }
            AddPhotoByFiles(photoPaths2);
        }
        #endregion

        #region 获取产品实体的所有照片
        /// <summary>
        /// 获取产品实体的所有照片
        /// </summary>
        /// <param name="photoPaths"></param>
        /// <param name="currentPath"></param>
        private void GetPhotoPathsOfProduct(List<string> photoPaths, string currentPath)
        {
            string[] subDirectorys = Directory.GetDirectories(currentPath);
            foreach (string subDirectory in subDirectorys)
            {
                GetPhotoPathsOfProduct(photoPaths, subDirectory);
            }
            string[] subFiles = GetFilesByPatterns(currentPath, "*.jpg|*tif|*.jpeg|*.tiff");
            foreach (string subFile in subFiles)
            {
                photoPaths.Add(subFile);
            }
        }
        #endregion

        #region 新增产品实体
        /// <summary>
        /// 新增产品实体
        /// </summary>
        /// <param name="productPath"></param>
        private void AddNewProductEntity(string productPath)
        {
            if (DisplayMode == true)
            {
                spcProductDetail.Panel2.Controls.Clear();
                spcProductDetail.Panel2.Controls.Add(gcProduct);
                DisplayMode = false;
            }
            if (pProductFlow.Controls != null)
                pProductFlow.Controls.Clear();
            gcProduct.DataSource = null;
            //流程容器清空
            pProductFlow.Controls.Clear();
            DirectoryInfo productInfo, ctmInfo, shopInfo;
            string productRemark;
            if (DragType == 4)                 //客户目录指定的产品实体
            {
                ctmInfo = new DirectoryInfo(productPath);
                shopInfo = ctmInfo.Parent;
                productRemark = ctmInfo.Name;
            }
            else
            {
                productInfo = new DirectoryInfo(productPath);
                ctmInfo = productInfo.Parent;
                shopInfo = ctmInfo.Parent;
                productRemark = productInfo.Name;
            }
            //商户名称
            string shopName = shopInfo.Name;
            int shopId = getShopId(shopName);
            if (shopId == 0)
            {
                MessageBox.Show("当前商户不存在!", "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            //客户名称
            string ctmName = ctmInfo.Name;
            //产品默认备注
            //创建新产品
            txtOrderName.Text = ctmInfo.Name;
            txtCtmName.Text = ctmName;
            cbShopName.Text = shopName;
            StartOrderBLL.ProductInfo product = new StartOrderBLL.ProductInfo();
            product.CtmName = ctmName;
            product.Height = 0;
            int index1 = productPath.LastIndexOf("\\");
            string path1 = productPath.Substring(0, index1);
            int index2 = path1.LastIndexOf("\\");
            string path2 = path1.Substring(0, index2);
            string path3 = productPath.Substring(index2 + 1);
            string orilPath = path2 + "\\" + "已开单" + "\\" + path3;
            product.OrilOrderPath = orilPath;
            //product.PageNum = 1;                          //产品的P数等于照片数量

            product.PhotoAllArea = 0;
            product.PhotoNum = 0;
            product.Photos = new List<StartOrderBLL.STPhoto>();
            product.ProductBarCode = "2222222222";
            product.ProductCategoryID = 0;
            product.ProductCategoryName = "";
            product.ProductID = 0;
            product.ProductName = productRemark;                           //产品名称的前半部分
            product.ProductNum = 1;                                         //产品数量默认为1
            product.ProductRemark = productRemark;

            //加载产品的备注信息读取目录下的txt文件作为产品备注
            product.ProductRemark += " " + GetRemarkOfProduct(productPath);
            product.ProductSerialID = currentSerialID;
            product.ProductType = 1;                                        //1实体  2产品模板  3二者综合
            product.techs = new List<StartOrderBLL.STProductTech>();
            product.Unit = cbUnit.Text.Trim();
            product.Width = 0;
            product.ProductTypeCode = 1;                                //产品默认是需要设计的产品

            ListProduct.Add(product);
            currentProduct = product;

            //设置当前产品照片的数据源
            gcProduct.DataSource = product.Photos;

            //产品名称
            txtProductName.Text = product.ProductName;
            spinProductNum.Text = product.ProductNum.ToString();
            spinPageNum.Text = product.PageNum.ToString();
            txtProductRemark.Text = product.ProductRemark;

            //新增产品系列增1
            currentSerialID++;
            //加载产品照片
            AddPhotosOfProduct(productPath);

            //根据商户名称设置商户特有产品
            cbShopName_SelectedIndexChanged(new object(), new EventArgs());
            //获取默认纸型纸面
            //var demom=ListPaperType.FirstOrDefault(pt => pt.PaperTypeID == product.PaperTypeID);
            //if (demom.PaperTypeID == 0)
            //{
                product.PaperTypeID = ShopPaperTypeID;
                product.PaperTypeName = ShopPaperTypeName;
            ////}
            ////else
            ////{
            //    product.PaperTypeID = product.PaperTypeID;
            //    product.PaperTypeName = product.PaperTypeName;
            //}
            product.PaperFaceID = ShopPaperFaceID;
            product.PaperFaceName = ShopPaperFaceName;
           
            //保存产品的原路径，用于移动开单目录
            currentProduct.OrilOrderPath2 = productPath;

            //设置产品照片数量与面积
            //SetPhotoNumAndArea(currentProduct.productTypeRemark);                      //参数需要改变

            spinProductNum.Text = "1";
            spinPageNum.Text = lblPhotoNum.Text;

            product.PageNum = Convert.ToInt32(spinPageNum.Text);
            gcProductList.RefreshDataSource();
            //最新的新增行获得焦点
            SetProductListFocusRow(currentSerialID - 1);
            //crc校验
            if (IsNeedCheckPhotoRepeat)
            {
                try
                {
                    int r = CrcCheck(currentProduct, "new");
                    if (r == 1)
                        MessageBox.Show("与照片重复验证服务端已断开，验证无效。如果要继续验证，请重启开单。", "确定", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
                catch (Exception e)
                {
                    if (e is SocketException)
                    {
                        MessageBox.Show("照片重复验证服务端异常或服务未启动。如果要执行验证，请重启服务，再重启开单！。", "确定", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                }
            }
        }

        private string GetRemarkOfProduct(string productPath)
        {
            StringBuilder productRemark = new StringBuilder();
            string CtmContext = GetCtmContext(productPath);
            GetTXTContext(productPath, productRemark);

            return CtmContext + productRemark.ToString();
        }

        private void GetTXTContext(string inStrPath, StringBuilder outContext)
        {
            string[] strDir = Directory.GetDirectories(inStrPath);
            DirectoryInfo faceInfo = new DirectoryInfo(inStrPath);
            FileInfo[] faceArrInfo = faceInfo.GetFiles("*.txt");
            //string strContext = "";
            foreach (FileInfo fileInfo in faceArrInfo)
            {
                StreamReader reader = new StreamReader(fileInfo.FullName, System.Text.Encoding.GetEncoding("gb2312"));
                outContext.Append(reader.ReadToEnd());
                outContext.Append(@"|");//文件分隔符
                reader.Close();
            }
            if (strDir.Length > 0)
            {
                foreach (string s in strDir)
                {
                    GetTXTContext(s, outContext);
                }
            }
            else
            {
                DirectoryInfo directoryInfo = new DirectoryInfo(inStrPath);
                FileInfo[] fileArrInfo = directoryInfo.GetFiles("*.txt");
                //string strContext = "";
                foreach (FileInfo fileInfo in fileArrInfo)
                {
                    StreamReader reader = new StreamReader(fileInfo.FullName, System.Text.Encoding.GetEncoding("gb2312"));
                    outContext.Append(reader.ReadToEnd());
                    outContext.Append(@"|");//文件分隔符
                    reader.Close();
                }

            }
        }
        public string GetCtmContext(string inProductPath)
        {
            DirectoryInfo directoryInfo = new DirectoryInfo(inProductPath);
            DirectoryInfo parentDir = directoryInfo.Parent;

            FileInfo[] fileArrInfo = parentDir.GetFiles("*.txt");
            string strContext = "";
            foreach (FileInfo fileInfo in fileArrInfo)
            {
                StreamReader reader = new StreamReader(fileInfo.FullName, System.Text.Encoding.GetEncoding("gb2312"));
                strContext += reader.ReadToEnd();
                strContext += @"|";//文件分隔符
                reader.Close();
            }
            return strContext;
        }

        #endregion



        #region 获取shopId
        /// <summary>
        /// 获取shopId
        /// </summary>
        /// <param name="shopName"></param>
        /// <returns></returns>
        public int getShopId(string shopName)
        {
            foreach (StartOrderBLL.STShop shop in ListShop)
            {
                if (shop.ShopName == shopName)
                {
                    return shop.ShopID;
                }
            }
            return 0;
        }
        #endregion

        #region 模板匹配实体
        /// <summary>
        /// 模板匹配实体
        /// </summary>
        private void AddModelForProduct(int productID)
        {
            for (int i = 0; i < productListShop.Count; i++)
            {
                if (productListShop[i].ProductID == productID)
                {
                    //加载参数
                    txtProductName.Text = productListShop[i].ProductName;
                    //公共参数
                    currentProduct = AddModelCommonPara(productListShop[i], currentProduct);
                    //商户特有的参数
                    int shopId = 0;
                    string shopName = cbShopName.Text;
                    foreach (StartOrderBLL.STShop shop in ListShop)
                    {
                        if (shop.ShopName == shopName)
                        {
                            shopId = shop.ShopID;
                            break;
                        }
                    }
                    //if (shopId != 0)
                    //{
                    //    //加载商户特有的参数
                    //    List<string> shopParas = SOBLL.GetShopParas(shopId, productID);
                    //    if (shopParas.Count == 2)
                    //    {
                    //        currentProduct.PaperFaceName = shopParas[0];
                    //        currentProduct.PaperTypeName = shopParas[1];
                    //    }
                    //}
                    currentProduct.ProductType = 3;                                     //1产品实体 2模板 3二者综合
                    //计算当前产品的预计用时
                    ComputeProductHours();
                    //SetPhotoNumAndArea(currentProduct.productTypeRemark);
                    gcProduct.RefreshDataSource();
                    gcProductList.RefreshDataSource();
                    break;
                }
            }
        }
        #endregion

        #region 计算当前产品的预计用时
        /// <summary>
        /// 计算当前产品的预计用时
        /// </summary>
        private void ComputeProductHours()
        {
            double hours = 0;              //产品用时
            foreach (StartOrderBLL.STProductTech tech in currentProduct.techs)
            {
                hours += tech.NeedTime;
            }
            currentProduct.ProductHours = hours;
            if (hours > OrderHours)
            {
                OrderHours = hours;
                DateTime now = DateTime.Now;
                now = now.AddHours(OrderHours);
                dtYJCompleteTime.Text = now.ToString("yyyy-MM-dd HH:mm");
                dtFetchTime.Text = now.ToString("yyyy-MM-dd HH:mm");
            }
        }
        #endregion

        #region 根据用时最长的产品设置订单用时
        /// <summary>
        /// 根据用时最长的产品设置订单用时
        /// </summary>
        private void CompareMaxHour()
        {
            double maxHour = 0;
            foreach (StartOrderBLL.ProductInfo product in ListProduct)
            {
                if (product.ProductHours > maxHour)
                    maxHour = product.ProductHours;
            }
            OrderHours = maxHour;
            DateTime now = DateTime.Now;
            now = now.AddHours(maxHour);
            dtYJCompleteTime.Text = now.ToString("yyyy-MM-dd HH:mm");
            dtFetchTime.Text = now.ToString("yyyy-MM-dd HH:mm");
        }
        #endregion

        #region 修改照片高宽
        //修改照片高宽按钮
        private void tsModifyPhotoHW_Click(object sender, EventArgs e)
        {
            try
            {
                if (gvProduct.SelectedRowsCount == 0)
                {
                    MessageBox.Show("没有选中的照片", "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                FrmModifyPhotoHW modifyPhoto = new FrmModifyPhotoHW();
                modifyPhoto.StartOrder = this;
                modifyPhoto.Unit = cbUnit.Text;
                if (DialogResult.OK == modifyPhoto.ShowDialog())
                {
                    float realH = 0, realW = 0;
                    switch (cbUnit.Text)
                    {
                        case "厘米(cm)":
                            realH = ModifyPhotoHeight / (float)2.54;
                            realW = ModifyPhotoWidth / (float)2.54;
                            break;
                        case "英寸(in)":
                            realH = ModifyPhotoHeight;
                            realW = ModifyPhotoWidth;
                            break;
                        case "米(m)":
                            realH = ModifyPhotoHeight * 100 / (float)2.54;
                            realW = ModifyPhotoWidth * 100 / (float)2.54;
                            break;
                        case "毫米(mm)":
                            realH = ModifyPhotoHeight / 10 / (float)2.54;
                            realW = ModifyPhotoWidth / 10 / (float)2.54;
                            break;
                    }
                    int[] indexes = gvProduct.GetSelectedRows();
                    foreach (int index in indexes)
                    {
                        StartOrderBLL.STPhoto photo = gvProduct.GetRow(index) as StartOrderBLL.STPhoto;
                        photo.PhotoStandardHCompute = realH;
                        photo.PhotoStandardWCompute = realW;
                        photo.PhotoArea = string.Format("{0:0.####}", ModifyPhotoHeight * ModifyPhotoWidth);
                        photo.PhotoAreaStandard = string.Format("{0:0.####}", realH * realW);
                        photo.PhotoHW = string.Format("{0:0.####}", ModifyPhotoHeight) + "×" + string.Format("{0:0.####}", ModifyPhotoWidth);
                        photo.PhotoHWStandard = string.Format("{0:0.####}", realH) + "×" + string.Format("{0:0.####}", realW);
                        photo.IsModifySize = true;
                    }
                    gcProduct.RefreshDataSource();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
        #endregion

        #region 展开与关闭左边目录树
        private void tsPath_Click(object sender, EventArgs e)
        {
            if (tsPath.Text == "展开目录")                                              //当前目录是关闭的
            {
                spcSecond.PanelVisibility = SplitPanelVisibility.Both;
                tsPath.Text = "隐藏目录";
            }
            else
            {
                spcSecond.PanelVisibility = SplitPanelVisibility.Panel2;
                tsPath.Text = "展开目录";
            }
        }
        #endregion
        //-----------------------------------------------
        //-------------左边目录树的操作结束--------------
        //-----------------------------------------------

        private void dtYJCompleteTime_TextChanged(object sender, EventArgs e)
        {
            bool IsOrderBagExist = SOBLL.IsOrderBagExist(txtOrderBagCode.Text.Trim());
        }

        private void dtFetchTime_Closed(object sender, DevExpress.XtraEditors.Controls.ClosedEventArgs e)
        {
            if (IsSetFetchTime == false)       //还未手动设置取件时间,则取件时间随预计完成时间变化
                //dtFetchTime.Text = dtYJCompleteTime.DateTime.Date.ToString("yyyy-MM-dd");
                dtFetchTime.Text = dtYJCompleteTime.DateTime.ToString();
        }

        //当订单包号失去焦点，判断当前包号是否已存在
        private void txtOrderBagCode_Properties_Leave(object sender, EventArgs e)
        {
            if (btnCodeType.Text == "自动")//只有在自动时，才进行包号检查
            {
                string bagCode = txtOrderBagCode.Text;
                bool IsOrderBagExist = SOBLL.IsOrderBagExist(bagCode);
                if (IsOrderBagExist)
                {
                    MessageBox.Show("订单包号已存在，请重新输入！", "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    txtOrderBagCode.Focus();
                }
                IsOrderBagExists = IsOrderBagExist;
            }
        }

        #region 清空订单信息
        //清空订单信息
        private void tsClearOrder_Click(object sender, EventArgs e)
        {
            try
            {
                if (DialogResult.Yes == MessageBox.Show("确定要清空订单吗?", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Warning))
                {
                    while (ListProduct.Count != 0)
                    {
                        int delIndex = gvProductList.GetSelectedRows()[0];
                        StartOrderBLL.ProductInfo product = gvProductList.GetRow(delIndex) as StartOrderBLL.ProductInfo;

                        string removePath = product.OrilOrderPath2;          //待删除产品的路径

                        int productSerialID = product.ProductSerialID;
                        DeleteProduct(productSerialID, removePath, true);
                        gcProductList.RefreshDataSource();
                        AfterDeleted();
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
        #endregion

        //助记码筛选
        private void txtZJM_EditValueChanged(object sender, EventArgs e)
        {
            try
            {
                if (txtZJM.Text == "")
                    return;
                if (ListProductDisplayShop == null)
                    return;
                if (xtraTabControl1.SelectedTabPage == xtraTabPage1)
                {
                    xtraTabControl1.SelectedTabPage = xtraTabPage2;
                }
                string code = txtZJM.Text.ToUpper();
                SXList.Clear();
                foreach (StartOrderBLL.STProductDisplay pd in ListProductDisplayShop)
                {
                    if (pd.ZJCode.Contains(code))
                    {
                        SXList.Add(pd);
                    }
                }
                AddProduct(SXList);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }

        }

        #region 照片属性有改变
        //照片属性有改变
        private void gvProduct_CellValueChanging(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {

            StartOrderBLL.STPhoto photo = gvProduct.GetRow(e.RowHandle) as StartOrderBLL.STPhoto;

            if (e.Column.FieldName == "PhotoNum")
            {
                int pn = 0;
                try
                {
                    pn = Convert.ToInt16(e.Value);
                }
                catch (Exception)
                {
                    MessageBox.Show("请输入正整数！", "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                photo.PhotoNum = pn;
            }
            else if (e.Column.FieldName == "PhotoRemark")
                photo.PhotoRemark = e.Value.ToString();
            else if (e.Column.FieldName == "PhotoTypeName")
            {
                string photoTypeName = e.Value.ToString();
                StartOrderBLL.STPaperType type = ListPaperType.FirstOrDefault(p => p.PaperTypeName == photoTypeName);
                photo.PhotoTypeID = type.PaperTypeID;
                photo.PhotoTypeName = type.PaperTypeName;

                //photo
            }
            else if (e.Column.FieldName == "PhotoFaceName")
            {
                string photoFaceName = e.Value.ToString();
                StartOrderBLL.STPaperFace type = ListPaperFace.FirstOrDefault(p => p.PaperFaceName == photoFaceName);
                photo.PhotoFaceID = type.PaperFaceID;
                photo.PhotoFaceName = type.PaperFaceName;
            }

        }
        #endregion

        /// <summary>
        /// 修改选中照片的数量
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsModifyPhotoNum_Click(object sender, EventArgs e)
        {
            try
            {
                if (gvProduct.GetSelectedRows().Count() > 0)
                {
                    Cursor = Cursors.WaitCursor;
                    FrmPhotoNum frm = new FrmPhotoNum();
                    frm.frm = this;
                    if (DialogResult.OK == frm.ShowDialog())
                    {
                        int[] indexes = gvProduct.GetSelectedRows();
                        foreach (int index in indexes)
                        {
                            StartOrderBLL.STPhoto photo = gvProduct.GetRow(index) as StartOrderBLL.STPhoto;
                            photo.PhotoNum = PhotoNum;
                        }
                        gcProduct.RefreshDataSource();
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确定", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            finally
            {
                Cursor = Cursors.Default;
            }
        }

        #region 产品刷新按钮
        /// <summary>
        /// 产品刷新按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void lblRefreshProduct_Click(object sender, EventArgs e)
        {
            try
            {
                xtraTabControl1.SelectedTabPage = xtraTabPage1;
                //获取商户特有的产品集合
                string shopName = cbShopName.Text;
                int shopId = 0;
                foreach (StartOrderBLL.STShop s in ListShop)
                {
                    if (s.ShopName == shopName)
                    {
                        shopId = s.ShopID;
                        break;
                    }
                }

                //移除对Grid的引用
                foreach (DevExpress.XtraNavBar.NavBarGroup g in bcProductCommon.Groups)
                {
                    if (g.ControlContainer != null && g.ControlContainer.Controls.Contains(gcProductCategoryShop))
                    {
                        g.ControlContainer.Controls.Remove(gcProductCategoryShop);
                        break;
                    }
                }
                bcProductCommon.Groups.Clear();
                if (shopId == 0)
                    return;
                productListShop = SOBLL.GetShopProductList(shopId);

                ListProductDisplayShop = new List<StartOrderBLL.STProductDisplay>();
                foreach (StartOrderBLL.ProductInfo s in productListShop)
                {
                    StartOrderBLL.STProductDisplay display = new StartOrderBLL.STProductDisplay();
                    display.ProductID = s.ProductID;
                    display.ProductName = s.ProductName;
                    display.ProductCategoryID = s.ProductCategoryID;
                    display.ProductCategoryName = s.ProductCategoryName;
                    float rh = s.Height;
                    float rw = s.Width;
                    display.ProductHW = string.Format("{0:0.##}", rh) + "×" + string.Format("{0:0.##}", rw);
                    display.ProductH = rh;
                    display.ProductW = rw;
                    display.ZJCode = s.ZJCode;
                    ListProductDisplayShop.Add(display);
                }

                var groups = ListProductDisplayShop.GroupBy(p => p.ProductCategoryID);


                foreach (var group in groups)
                {
                    foreach (var item in group)
                    {
                        DevExpress.XtraNavBar.NavBarGroup g = new DevExpress.XtraNavBar.NavBarGroup();
                        g.Caption = item.ProductCategoryName;
                        g.Tag = item.ProductCategoryID;
                        bcProductCommon.Groups.Add(g);
                        break;
                    }
                }
                if (bcProductCommon.Groups != null && bcProductCommon.Groups.Count == 1)
                {
                    DevExpress.XtraNavBar.NavBarGroup group = new DevExpress.XtraNavBar.NavBarGroup();
                    group.Caption = "";
                    group.Expanded = false;
                    bcProductCommon.Groups.Add(group);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
        #endregion

        #region 数据结构
        /*
        /// <summary>
        /// 创建照片信息结构
        /// </summary>
        /// <returns></returns>
        public DataTable CreatePhotoInfoDT()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add(new DataColumn("PhotoName", typeof(string)));            //照片名称
            dt.Columns.Add(new DataColumn("PhotoSize", typeof(string)));            //照片大小
            dt.Columns.Add(new DataColumn("PhotoHWStandard", typeof(string)));      //标准高宽
            dt.Columns.Add(new DataColumn("PhotoAreaStandard", typeof(float)));     //标准面积
            dt.Columns.Add(new DataColumn("PhotoHW", typeof(string)));              //高宽
            dt.Columns.Add(new DataColumn("PhotoArea", typeof(float)));             //面积
            dt.Columns.Add(new DataColumn("Unit", typeof(string)));                 //单位
            dt.Columns.Add(new DataColumn("PhotoRemark", typeof(string)));          //照片备注
            return dt;
        }*/

        /// <summary>
        /// 照片列表与缩略图的大对象
        /// </summary>
        public class PhotoListAndThumb
        {
            public StartOrderBLL.STPhoto Item { get; set; }   //照片列表
            public RasterImageListItem Thumb { get; set; }  //缩略图
            public bool ThumbIsAdded { get; set; }  //缩略图是否已加载
        }

        #endregion

        //设置服务器路径
        private void btnSetServerPath_Click(object sender, EventArgs e)
        {
            try
            {
                if (DialogResult.OK == folderBrowserDialog1.ShowDialog())
                {
                    string serverPath = folderBrowserDialog1.SelectedPath;
                    Properties.Settings.Default.ServerPath = serverPath;
                    Properties.Settings.Default.Save();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        //打开服务器目录
        private void btnOpenServerPath_Click(object sender, EventArgs e)
        {
            try
            {
                if (tvOrderPath.SelectedNode == null)
                {
                    MessageBox.Show("没有节点被选中！", "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                //string serverPath = Properties.Settings.Default.ServerPath;
                //if (Directory.Exists(serverPath))
                //{
                //    ShellExecute(IntPtr.Zero, new StringBuilder("open"), new StringBuilder("explorer.exe"),
                //                             new StringBuilder(serverPath), new StringBuilder(string.Empty), 1);
                //}
                string serverPath = tvOrderPath.SelectedNode.Tag.ToString();
                if (Directory.Exists(serverPath))
                {
                    ShellExecute(IntPtr.Zero, new StringBuilder("open"), new StringBuilder("explorer.exe"),
                                             new StringBuilder(serverPath), new StringBuilder(string.Empty), 1);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        private void gvProductList_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            //保存上个产品明细
            if (e.FocusedRowHandle < 0)
                return;
            SaveCurrentProduct();
            isAddOldTech = true;                                                //表示是已添加的产品
            SetProductDetail(GetProductSerialId(e.FocusedRowHandle));
        }

        //设置常用产品数量
        private void btnSetUsuallyUse_Click(object sender, EventArgs e)
        {
            try
            {
                int num = 0;
                try
                {
                    num = Convert.ToInt32(txtUsuallyUse.Text.Trim());
                }
                catch
                {
                    MessageBox.Show("请输入正整数！", "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                if (num <= 0)
                {
                    MessageBox.Show("请输入正整数！", "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                Properties.Settings.Default.UsuallyUseNum = num;
                Properties.Settings.Default.Save();
                AddUsuallyUseProducts();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        #region 检查照片是否重复
        /// <summary>
        /// 检查照片是否重复
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cbPhotoRepeatCheck_CheckedChanged(object sender, EventArgs e)
        {
            if (cbPhotoRepeatCheck.Checked)
            {
                IsNeedCheckPhotoRepeat = true;
            }
            else
            {
                IsNeedCheckPhotoRepeat = false;
            }
            //ConfigurationManager.AppSettings.Set("IsCheckCrcCode", IsNeedCheckPhotoRepeat ? "True" : "False");
            ////Properties.Settings.Default.userCrc = IsNeedCheckPhotoRepeat;           //保存是否重复校验，下次的初始化值
            ////Properties.Settings.Default.Save();
            ModifyConfigurationOP.SetConfig("IsCheckCrcCode", IsNeedCheckPhotoRepeat ? "True" : "False");
        }
        #endregion

        //单击对应目录
        private void tvOrderPath_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            try
            {
                string ccJb = e.Node.Name.Substring(e.Node.Name.Length - 1);
                if (ccJb == "4")       //如果是产品内的尺寸目录
                {
                    string ccPath = e.Node.Tag.ToString();
                    string[] files = GetFilesPath(ccPath);
                    if (currentProduct != null)
                    {
                        foreach (StartOrderBLL.STPhoto photo in currentProduct.Photos)
                        {
                            if (files.Contains(photo.PhotoFullPath))
                            {
                                photo.IsInDirectory = true;
                            }
                            else
                            {
                                photo.IsInDirectory = false;
                            }
                        }
                    }
                    else
                    {
                        return;
                    }
                    gcProduct.RefreshDataSource();
                    //单击同时选中目录内所有的照片
                    List<int> focusedRows = new List<int>();        //需获得焦点的集合
                    for (int i = 0; i < gvProduct.RowCount; i++)
                    {
                        StartOrderBLL.STPhoto photo = gvProduct.GetRow(i) as StartOrderBLL.STPhoto;
                        if (files.Contains(photo.PhotoFullPath))
                        {
                            focusedRows.Add(i);
                        }
                    }
                    if (focusedRows.Count > 0)
                    {
                        gvProduct.ClearSelection();                 //先清除以前的焦点
                        foreach (int i in focusedRows)              //设置当前点击目录所有照片的焦点
                        {
                            gvProduct.SelectRow(i);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        //理件
        private void tsDispose_Click(object sender, EventArgs e)
        {
            //try
            //{
            //    Cursor = Cursors.WaitCursor;
            //    PickupPhoto.FrmDisposeMain frm = PickupPhoto.FrmDisposeMain.GetInstance(UserID);
            //    frm.UserId = UserID;
            //    frm.StartOrderTotalPath = TotalPath;
            //    frm.Show();
            //    Cursor = Cursors.Default;
            //}
            //catch (Exception ex)
            //{
            //    Cursor = Cursors.Default;
            //    MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            //}
        }

        //界面快捷键
        private void FrmStartOrder_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Modifiers == Keys.Alt && e.KeyCode == Keys.A)                     //alt+A快速设置调色员
            {
                Control.ControlCollection cs = pProductFlow.Controls;
                foreach (Control c in cs)
                {
                    if (c is LinkLabel && c.Name == "llTS")
                    {
                        lluser_Click(c, e);
                    }
                }
            }
        }

        private void cbPaperType_SelectedIndexChanged(object sender, EventArgs e)
        {
            // SaveCurrentProduct();

            int ptypeID = 0;
            string ptypeName = cbPaperType.Text.Trim();
            foreach (StartOrderBLL.STPaperType ptype in ListPaperType)
            {
                if (ptypeName == ptype.PaperTypeName)
                {
                    ptypeID = ptype.PaperTypeID;
                    break;
                }
            }
            if (currentProduct != null)
            {
                currentProduct.PaperTypeID = ptypeID;

                currentProduct.PaperTypeName = ptypeName;
                //currentProduct.Photos.ForEach(p => p.PhotoTypeID = ptypeID);
                //currentProduct.Photos.ForEach(p => p.PhotoTypeName = ptypeName);

            }
            gcProductList.RefreshDataSource();
            gcProduct.RefreshDataSource();

        }

        private void txtCtmName_EditValueChanged(object sender, EventArgs e)
        {
            //SaveCurrentProduct();
        }

        private void cbPaperFace_SelectedIndexChanged(object sender, EventArgs e)
        {

            int pfaceID = 0;
            string pfaceName = cbPaperFace.Text.Trim();
            foreach (StartOrderBLL.STPaperFace pface in ListPaperFace)
            {
                if (pfaceName == pface.PaperFaceName)
                {
                    pfaceID = pface.PaperFaceID;
                    break;
                }
            }

            if (currentProduct != null)
            {
                currentProduct.PaperFaceID = pfaceID;

                currentProduct.PaperFaceName = pfaceName;
                //currentProduct.Photos.ForEach(p => p.PhotoFaceID = pfaceID);
                //currentProduct.Photos.ForEach(p => p.PhotoFaceName = pfaceName);

            }
            gcProductList.RefreshDataSource();
            gcProduct.RefreshDataSource();

        }

        private void cbPaperType_SelectedIndexChanged_1(object sender, EventArgs e)
        {

        }

        private void cbShopPaperType_SelectedIndexChanged(object sender, EventArgs e)
        {
            ShopPaperTypeName = cbShopPaperType.Text;
            gcProductList.RefreshDataSource();
            gcProduct.RefreshDataSource();
        }

        private void cbShopPaperFace_SelectedIndexChanged(object sender, EventArgs e)
        {
            ShopPaperFaceName = cbShopPaperFace.Text;
            gcProductList.RefreshDataSource();
            gcProduct.RefreshDataSource();

        }
        //设置不需要照片的产品
        private void ceProductWithoutPhoto_CheckedChanged(object sender, EventArgs e)
        {
            if (ceProductWithoutPhotoClick)//当鼠标点击时才激发一下事件
            {
                if (ceProductWithoutPhoto.Checked)
                {
                    if (currentProduct.ProductType == 2)//只有产品模板
                    {
                        currentProduct.ProductType = 4;//不需要照片的产品
                        SetPrioductWithoutProduct();
                    }
                    else
                    {
                        MessageBox.Show("该产品含有照片", "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);

                    }
                }
                else
                {
                    currentProduct.ProductType = 2;//恢复可以脱照片的状态
                    currentProduct.ProductName = currentProduct.ProductName.Replace("无照片_", "");
                    txtProductName.Text = currentProduct.ProductName;
                }
            }
        }
        /// <summary>
        /// 不包含照片的产品设置
        /// </summary>
        private void SetPrioductWithoutProduct()
        {


            //商户名称
            string shopName = cbShopName.Text;
            /*
            DirectoryInfo productInfo = new DirectoryInfo(productPath);
            DirectoryInfo ctmInfo = productInfo.Parent;
            DirectoryInfo shopInfo = ctmInfo.Parent;
            //商户名称
            string shopName = shopInfo.Name;*/
            int shopId = getShopId(shopName);
            if (shopId == 0)
            {
                MessageBox.Show("当前商户不存在,请在后台添加!", "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            //客户名称
            string ctmName = txtCtmName.Text;
            //加载产品照片
            //AddPhotosOfProduct(productPath);
            currentProduct.ProductType = 4;                                             //1实体  2产品模板  3二者综合4不需要照片的产品
            //匹配客户名称，商户名称，纸型，纸面,产品备注

            currentProduct.OrilOrderPath = "";
            currentProduct.CtmName = ctmName;
            txtCtmName.Text = ctmName;
            cbShopName.Text = shopName;
            //txtShopRequire.Text = productRemark;
            string productRemark = txtProductRemark.Text;
            currentProduct.ProductRemark = productRemark;
            currentProduct.CtmName = ctmName;
            //产品名称
            currentProduct.ProductName = "无照片_" + currentProduct.ProductName;
            txtProductRemark.Text = productRemark;
            txtProductName.Text = currentProduct.ProductName;
            //产品备注加上商户的备注
            txtProductRemark.Text += "\\" + txtShopRequire.Text;
            currentProduct.ProductRemark = txtProductRemark.Text;
            //根据商户名称设置商户特有产品
            // cbShopName_SelectedIndexChanged(new object(), new EventArgs());

            //保存产品的原路径，在移动时使用
            currentProduct.OrilOrderPath2 = "";
            SetEnableAndDisable((int)OrderInfoProductType.NoPhotoProduct);
            //设置产品照片数量与总面积
            // SetPhotoNumAndArea(currentProduct.productTypeRemark);
        }
        private void SetBackPrioductWithoutProduct()
        {

        }
        private void ceProductWithoutPhoto_Click(object sender, EventArgs e)
        {
            ceProductWithoutPhotoClick = true;
        }



        private void repositoryItemCheckedComboBoxEditCostType_Closed(object sender, DevExpress.XtraEditors.Controls.ClosedEventArgs e)
        {
            string str = "";
            foreach (DevExpress.XtraEditors.Controls.CheckedListBoxItem item in repositoryItemCheckedComboBoxEditCostType.Items)
            {
                if (item.CheckState.ToString() == "Checked")
                {
                    str += item.ToString() + ",";
                }

            }
            str = str.TrimEnd(',');
            if (str.Contains("设计"))
            {
                if (singleProductTech.Count < 0)
                {
                    MessageBox.Show("注意设计流程未添加，请先给产品添加模板再添加设计费用", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    StartOrderBLL.STProductTech tech = singleProductTech.FirstOrDefault(p => p.IsDesign == true);
                    if (tech != null)
                    {
                        Control.ControlCollection cs = pProductFlow.Controls;
                        foreach (Control cc in cs)
                        {
                            if (("设计").Equals(cc.Text))
                            {
                                ((CheckBox)cc).Checked = true;
                                break;
                            }
                        }
 
                    }
                    
                }

            }
            else if (str.Contains("修片"))
            {
                if (singleProductTech.Count < 0)
                {
                    MessageBox.Show("注意设计流程未添加，请先给产品添加模板再添加设计费用", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {

                    StartOrderBLL.STProductTech techXiu = singleProductTech.FirstOrDefault(p => p.TechName == "修片");
                    if (techXiu != null)
                    {
                        Control.ControlCollection cs = pProductFlow.Controls;
                        foreach (Control cc in cs)
                        {
                            if (("修片").Equals(cc.Text))
                            {
                                ((CheckBox)cc).Checked = true;
                                break;
                            }
                        }

                    }

                }

            }
            else { }
            ((MINERP.BLL.CustomerManage.StartOrderBLL.ProductInfo)gvProductList.GetFocusedRow()).StringCostItems = str;
        }

        private void spinEditPhotoNum_EditValueChanged(object sender, EventArgs e)
        {
            int photoNum = Convert.ToInt32(spinEditPhotoNum.Text);
            List<StartOrderBLL.STPhoto> listPhoto = ((StartOrderBLL.ProductInfo)gvProductList.GetFocusedRow()).Photos;
            listPhoto.ForEach(p => p.PhotoNum = photoNum);
            gcProduct.RefreshDataSource();
        }

        private void gvProductList_RowCellClick(object sender, RowCellClickEventArgs e)
        {
            if (e.RowHandle == 0)
            {

                // SaveCurrentProduct();
            }
        }

        private void checkEditOutReturn_CheckedChanged(object sender, EventArgs e)
        {
            if (currentProduct == null)
            {
                return;
            }
            if (ceProductOutReturnClick)//当鼠标点击时才激发一下事件
            {
                if (checkEditOutReturn.Checked)
                {

                    currentProduct.ProductPayType = (int)OrderInfoType.OutReturnInfo;
                }
                else
                {
                    currentProduct.ProductPayType = (int)OrderInfoType.Normal;

                }
            }
        }

        private void spcProductDetail_Panel1_Paint(object sender, PaintEventArgs e)
        {

        }

        private void checkEditOutReturn_Click(object sender, EventArgs e)
        {
            ceProductOutReturnClick = true;
        }

        private void gcProductList_Click(object sender, EventArgs e)
        {

        }

        private void comboBoxRemarkLink_SelectedIndexChanged(object sender, EventArgs e)
        {
            txtProductRemark.Text = comboBoxRemarkLink.Text + txtProductRemark.Text;
        }

        private void dtFetchTime_EditValueChanged(object sender, EventArgs e)
        {

        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            try
            {
                gvProductList.SaveLayoutToXml(LayoutPath + "\\StartOrdergvProductList.Xml");
                gvProduct.SaveLayoutToXml(LayoutPath + "\\StartOrdergvProduct.Xml");
                MessageBox.Show("保存成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

            }
            catch
            {
                MessageBox.Show("格式未保存成功，请重新尝试","提示",MessageBoxButtons.OK,MessageBoxIcon.Information);
            }

        }

        private void linkLabelCopy_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            Clipboard.SetDataObject(txtOrderBagCode.Text);


        }

        private void spcProduct_Panel1_Paint(object sender, PaintEventArgs e)
        {

        }




        private string[] GetFilesPath(string dirPath)
        {
            string[] file1 = Directory.GetFiles(dirPath, "*.jpg");
            string[] file2 = Directory.GetFiles(dirPath, "*.tif");
            string[] file3 = Directory.GetFiles(dirPath, "*.jpeg");
            string[] file4 = Directory.GetFiles(dirPath, "*.tiff");
            string[] files = file1.Concat(file2).Concat(file3).Concat(file4).ToArray();
            return files;
        }

        private FileInfo[] GetFileInfo(string dirPath)
        {
            DirectoryInfo ssubInfo = new DirectoryInfo(dirPath);
            FileInfo[] sssfile1 = ssubInfo.GetFiles("*.jpg");
            FileInfo[] sssfile2 = ssubInfo.GetFiles("*.tif");
            FileInfo[] sssfile3 = ssubInfo.GetFiles("*.jpeg");
            FileInfo[] sssfile4 = ssubInfo.GetFiles("*.tiff");
            FileInfo[] sssfile = sssfile1.Concat(sssfile2).Concat(sssfile3).Concat(sssfile4).ToArray();
            return sssfile;
        }



        //private void gvProduct_TypeSelectedValueChanged(object sender, System.EventArgs e)
        //{
        //   // CurrPhoto.PhotoTypeName = ((DevExpress.XtraEditors.ComboBoxEdit)sender).SelectedText;
        //}
        //private void gvProduct_FaceSelectedValueChanged(object sender, System.EventArgs e)
        //{
        //   // CurrPhoto.PhotoFaceName = ((DevExpress.XtraEditors.ComboBoxEdit)sender).SelectedText;
        //}










    }
}
